public class FirstServletClass extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = -45872253821246793L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException ,IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
HttpSession session = request.getSession();
if(request.getParameter("userName")!=null){
session.setAttribute("UserName", request.getParameter("userName")) ;
}
pw.print("HI From Server <br/>");
pw.print("Accessing Value from Response object "+request.getParameter("userName")+"<br/>");
pw.print("Accessing Value from Session object "+(String)session.getAttribute("userName")+"<br/>");
System.out.println("Get Method Called");
}
}
点击网址&#34; http://localhost:8080/Servlets/niteshServlet?userName=nitesh&#34;以下产出即将到来:
HI From Server
从Response对象中访问值nitesh
从Session对象访问值null
请建议,我哪里错了?
答案 0 :(得分:1)
在会话中设置userName时,您使用的属性名称为UserName
,但您尝试使用userName
访问它。在两种情况下都使用camel case属性名称。
将代码更改为:
session.setAttribute("userName", request.getParameter("userName"));
答案 1 :(得分:0)
您正在设置属性UserName
,但检索属性userName
。它区分大小写。