session().getAttribute is returning null

时光总嘲笑我的痴心妄想 提交于 2021-01-29 04:35:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!