I just started exploring Java Servlets and JSP and am a little confused about the sessions object. Inside a servlet I have this:
public class SampleServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
HttpSession session = request.getSession(true);
session.setAttribute("_session", "_value");
response.sendRedirect("page2.jsp");
}
}
Now, inside page2.jsp, there is a session object as well, but when I do this
<%
out.print(session.getAttribute("_session"))
%>
it does not seem to get the value (as if it is not set). I tried setting a boolean attribute to true but in the jsp page it returns a false. Can someone tell me the right way of doing this? As to what I am trying to do, I want to share some session variables.
Use request.getRequestDispatcher().forward() instead of response.sendRedirect();
So your code would be:
Basically, response.sendRedirect() does not preserve session info, so it’s not there when the jsp gets it. request.forward() does preserve the session.
See http://www.coderanch.com/t/170618/java-Web-Component-SCWCD/certification/sendRedirect-Vs-requestdispatcher-forward