[Servlet & amp; JSP] HttpSession session management

Source: Internet
Author: User

[Servlet & JSP] HttpSession session management

We can save the information that must be shared during the session in HttpSession to make it an attribute. If you disable the Cookie reception function of the browser, you can rewrite the http session to continue its session management function.

HttpSession usage

In Servlet/JSP, if you want to manage sessions, you can use the getSession () method of HttpServletRequest to obtain the HttpSession object. The statement is as follows:

HttpSession session = request.getSession();

The getSession () method has two versions. A boolean value can be input in another version. The default value is true, indicating that if no HttpSession instance exists, a new object is created. If the value is false, indicates that if no HttpSession instance exists, null is returned directly.

SetAttribute () and getAttribute () are the most common methods in HttpSession. You can set and obtain attributes in an object. By default, the obtained HttpSession is the same instance before the browser is closed. If you want to invalidate the current HttpSession during this session, you can execute the invalidate () method of HttpSession. One time to use is to implement the logout mechanism. An example is as follows:

Login. java:

@WebServlet("/login.do")public class Login extends HttpServlet{    protected void processRequest(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {        String username = request.getParameter("username");        String password = request.getParameter("password");        if ("abc".equals(username) && "123".equals(password)) {            request.getSession().setAttribute("login", username);            request.getRequestDispatcher("user.jsp")                .forward(request, response);        } else {            response.sendRedirect("login.html");        }    }    protected void doGet(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {        processRequest(request, response);    }    protected void doPost(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {        processRequest(request, response);    }}

When logging on, if the user name and password are correct, the HttpSession will be obtained and a login attribute will be set to indicate that the user has completed the login action. For other servlets/JSPs, if you can obtain the login attribute from HttpSession, you can basically determine a logged-on user. This type of attribute is used to identify whether a user is logged on, it is usually called a Login Token ). In the above example, after successful login, the system will forward it to the user interface.
User. jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<body>    <form action="login.do" method="post">        username:<input type="text" name="username" /><br />        password:<input type="password" name="password" /><br />        <input type="submit" value="Sign in" />    </form></body>

Login.html
 

<body>    <form action="login.do" method="post">        username:<input type="text" name="username" /><br />        password:<input type="password" name="password" /><br />        <input type="submit" value="Sign in" />    </form></body>Logout.java:
@WebServlet("/logout.do")public class Logout extends HttpServlet{    protected void doGet(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {        request.getSession().invalidate();        response.sendRedirect("login.html");    }}


After the invalidate () of HttpSession is specified, the container destroys and recycles the HttpSession object. If you execute getSession () of HttpServletRequest again, the obtained HttpSession is another new object.

HttpSession management principles

When the getSession () of HttpServletRequest is executed, the web Container creates an HttpSession object. Each HttpSession has a special ID, which is called the Session ID. You can execute getID () of HttpSession to obtain the Session ID. By default, this Session ID uses cookies to store it in the browser. In Tomcat, the Cookie name is JSESSIONID, and the number is the Session ID obtained by getID.

Each HttpSession has a special Session ID. When a browser requests an application, it sends the Session ID stored in the Cookie to the application, the web Container extracts the corresponding HttpSession object based on the Session ID, so that the Session data of each browser can be obtained.

Therefore, when you use HttpSession for Session management, the data set as the attribute is stored on the server side, and the Session ID is stored in the browser using cookies by default. When the Cookie of the Session ID stored in the web container is set to disabled, the browser will become invalid. When the browser re-opens the application, the new HttpSession object is obtained through getSession.

Because HttpSession occupies memory space, do not store large objects that consume resources in the attributes of HttpSession. If necessary, you can remove the attributes or execute invalidate () when you do not need to use HttpSession () make HttpSession invalid.

When the browser is closed, the Cookie on the browser will immediately expire, instead of HttpSession.

You can run the setMaxInactiveInterval () method of HttpSession to set the length of time when the browser does not request an application. Then, the HttpSession will automatically expire, in seconds ". You can also set the default expiration time of HttpSession in web. xml, but note that the time unit set here is "Minute ". For example:

<web-app ...>    <session-config>        <session-timeout>30</session-timeout>    </session-config></web-app>

When the Cookie that saves the Session ID is set to close the browser, it becomes invalid. If you want to save the information after closing the browser, you must perform the Cookie operation on your own. For example, you can complete the automatic logon mechanism.

HttpSession and URL rewriting

If you still want to use HttpSession for Session management when disabling cookies, you can use the URL rewriting method to respond to a hyperlink in the browser and append the Session ID after the hyperlink URL, when a user clicks a hyperlink, the Session ID is sent to the web application as a GET request.

If you want to use the URL rewriting method to send the Session ID, you can use the encodeURL () of HttpServletRequest to generate the required URL rewriting. When the container tries to get an HttpSession instance, if the Cookie with Session ID can be obtained from the HTTP request, encodeURL () will output the URL set to it intact; if you cannot obtain a Cookie with the Session ID from an HTTP request (usually when the browser disables the Cookie), encodeURL () will automatically generate a URL with the Session ID.

If encdeURL () is executed, the container does not know whether to disable the Cookie when the browser requests the website for the first time. Therefore, the container uses the Cookie (send the set-cookie header) and URL rewriting. Therefore, if the Servlet has the following statement, no matter whether the browser disables the Cookie or not, the URL of the Session ID will be displayed during the first request.

request.getSession();out.println(response.encodeURL("index.jsp"));

When a request is sent again, if the browser does not disable the Cookie, the container can obtain the Session ID from the Cookie (from the cookie header). In this case, encodeURL () will only output index. jsp. If the browser disables the Cookie, encodeURL () continues to compile the Session ID on the URL.

The encodeRedirectURL () method of HttpServletResponse can be used to compile the Session ID on the URL when the browser is redirected.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.