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.
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
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") );
this is wrong:
request.getSession(true).setAttribute(request.getParameter("name"), userName );
I think it should be
request.getSession(true).setAttribute("userName", userName );
I think you inverted the two params. It should be like this:
request.getSession(true).setAttribute("userName", userName );
快速浏览一下我认为这可能有点类似并且可能有所帮助: JSP Session.getAttribute()值返回null
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.