If I have this code below in the doGet()
where I create a session object:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get request parameters for userID and password
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(userID.equals(user) && password.equals(pwd)){
HttpSession session = request.getSession();
session.setAttribute("user", "Pankaj");
//setting session to expiry in 30 mins
session.setMaxInactiveInterval(30*60);
Cookie userName = new Cookie("user", user);
userName.setMaxAge(30*60);
response.addCookie(userName);
response.sendRedirect("LoginSuccess.jsp");
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
I have a couple questions:
- When I create the session object at
HttpSession session = request.getSession();
is this when the session is created for the request for the first time or does the container already create the request when the request first comes in (before the call togetSession()
) - When I call
response.sendRedirect("LoginSuccess.jsp");
how is the session object available to access inLoginSuccess.jsp
? I am able tosession.getAttribute("user")
inLoginSuccess.jsp
but I am not sure how the session is passed to theLoginSuccess.jsp
? - Same goes for the cookie that is created
Cookie userName = new Cookie("user", user);
. In theLoginSuccess.jsp
I am able to docookie.getName().equals("user"))
. How is the cookie object passed toLoginSuccess.jsp
? Is that because ofresponse.addCookie(userName);
?