问题
I have a servlet which calls a jsp page. In the servlet I am retrieving the username provided at the login correctly. But after setting the same in session, when i access the called jsp page, its returning null.
Servlet Code:
public class AdminServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -4244742541587179390L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("name");
System.out.println("UserName: " + userName); // Here it prints the username properly
request.getSession(true).setAttribute(request.getParameter("name"), userName );
RequestDispatcher rd = request.getRequestDispatcher("upload.jsp");
rd.forward(request, response);
// response.sendRedirect("upload.jsp");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
JSP Code snippet where I am accessing this:
<label class="message">Welcome <%= session.getAttribute("userName") %></label>
What am I doing wrong here? Can anyone help please
回答1:
I think you inverted the two params. It should be like this:
request.getSession(true).setAttribute("userName", userName );
回答2:
you should get session value from the value of
request.getParameter("name");
or in servlet you need as follow:
request.getSession(true).setAttribute("userName",request.getParameter("name") );
回答3:
this is wrong:
request.getSession(true).setAttribute(request.getParameter("name"), userName );
I think it should be
request.getSession(true).setAttribute("userName", userName );
回答4:
Just had a quick look I think this might be a little similar and might help: JSP Session.getAttribute() value return null
来源:https://stackoverflow.com/questions/29968481/session-getattribute-is-returning-null