[ Team LiB ] |
Recipe 11.4 Checking if a Session Exists in an HttpServletRequestProblemYou want to check if a web application user has a valid session. SolutionUse the HttpServletRequest object's getSession(false) method to find out whether the HttpSession object is null. DiscussionSome web components are designed to monitor if a session is valid, then optionally redirect or forward the user to another web component based on the validity of the session. For example, imagine that a user makes a request to a component that expects to find a custom object stored in the session object, such as a "shopping cart." You want to check if the session is valid; however, you do not want to create a new session for the request if the session is not valid, because another web component farther back in the chain of application components is responsible for creating new sessions and populating them with shopping cart items. The user may have entered the web application at Step 3 instead of Step 1. In this case, if the session is invalid, the request is forwarded to another access point in the application (such as a login screen). If you call the HttpServletRequest object's getSession(false) method and the method returns false, then the user does not have a valid session and the request object has not created a new session for her.
Example 11-6 is a servlet that checks a user's session, then redirects the user to another web component if the session object is null. Example 11-6. Checking if a session is valid or notimport javax.servlet.*;
import javax.servlet.http.*;
public class SessionCheck extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
HttpSession session = request.getSession(false);
if (session == null){
response.sendRedirect("/myproj/login.jsp");
} else {
response.sendRedirect("/myproj/menu.jsp");
}
}
}
If the session in Example 11-6 is null, the servlet redirects the request to the login.jsp page at the context path /myproj. If the session object is valid, the request is redirected to the /myproj/menu.jsp component. See AlsoRecipe 11.1 and Recipe 11.3 on configuring the session timeout; Chapter 1 on web.xml; Chapter 7 of the Servlet v2.3 and 2.4 specifications on sessions; the session-tracking sections of Java Servlet Programming by Jason Hunter (O'Reilly) and JavaServer Pages by Hans Bergsten (O'Reilly). |
[ Team LiB ] |