In-depth analysis and research on httpsession

Source: Internet
Author: User

HTTP is a stateless protocol, which means that each time the client retrieves a webpage, a server connection must be opened separately. Therefore, the server does not record any information previously requested by the client.

There are three methods to maintain the session between the client and the server:

1. The network server can specify a unique session ID as a cookie to represent each client and identify the next request of this client.

This may not be an effective method, because many times the browser does not necessarily support cookies, so we do not recommend using this method to maintain sessions.

2. Rewrite the URL

For example, the http://baidu.com; sessionid = 12345, session identifier is sessionid = 12345, the server can use this data to identify the client.

In contrast, rewriting a URL is a better way. Even if the browser does not support cookies, it can work. However, the disadvantage is that you must dynamically specify the session ID for each URL, even if it is a simple HTML page.

3. In addition to the preceding methods, JSP uses the http session interface provided by servlet to identify a user and store all access information of the user.

The JSP Engine exposes hidden session objects to developers. With session objects, developers can easily store or retrieve data.

The following table lists some important methods for session objects:
1 Public object getattribute (string name)
Returns the object bound to the specified name in the session object. If the specified name does not exist, null is returned.
2 Public enumeration getattributenames ()
Returns the names of all objects in the session object.
3 Public long getcreationtime ()
Returns the time when the session object was created, in milliseconds, starting from the early morning of January 1, January 1, 1970.
4 Public String GETID ()
Returns the Session Object ID.
5 Public long getlastaccessedtime ()
Returns the last access time of the client, in milliseconds, starting from the early morning of January 1, January 1, 1970.
6 Public int getmaxinactiveinterval ()
The maximum returned time interval. In seconds, the servlet container will keep the session open during this time.
7 Public void invalidate ()
Unbind any objects bound to the session because the session is invalid.
8 Public Boolean isnew ()
Returns whether it is a new client or whether the client refuses to join the session.
9 Public void removeattribute (string name)
Removes the object with the specified name in the session.
10 Public void setattribute (string name, object value)
Use the specified name and value to generate an object and bind it to the session.
11 Public void setmaxinactiveinterval (INT interval)
Used to specify the time. In seconds, the servlet container will keep the session valid during this time.
How is it used in practical development?

Next we will use a simple example to view the usage of the session.

Web. xml

<servlet>    <servlet-name>Session</servlet-name>    <servlet-class>com.qzp.servlet.sessionServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>Session</servlet-name>    <url-pattern>/session</url-pattern>  </servlet-mapping>

Sessiontest. jsp

<Body> <form action = "session" method = "Post"> <input type = "Submit" value = "View session"> </form> </body>

Sessionservlet

Public class sessionservlet extends httpservlet {/*****/Private Static final long serialversionuid = 1l; @ overrideprotected void doget (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {// todo auto-generated method stubthis. doget (req, resp) ;}@ overrideprotected void dopost (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {httpsession session = req. getsession (); // get the session creation time // convert the date format date createtime = new date through simpledateformat (Session. getcreationtime (); simpledateformat ST1 = new simpledateformat ("Mm, DD, yyyy, HH, mm, SS, e"); string time1 = st1.format (createtime ); // obtain the last page access time date lastaccesstime = new date (Session. getlastaccessedtime (); simpledateformat st2 = new simpledateformat ("YYYY mm dd hh mm min SS sec e"); string time2 = st2.format (lastaccesstime ); // access the key-valuestring useridvalue = "0011" of the user's unique ID; // key-value of the number of visits // note the session construction method public void setattribute (string name, object value) // The key in this constructor is a string type variable; value is an object type variable int visitcountvalue; visitcountvalue = (integer) session. getattribute ("visitcount"); // determines whether it is a new user if (Session. isnew () {session. setattribute ("idkey", useridvalue); Session. setattribute ("visitcount", visitcountvalue);} visitcountvalue = visitcountvalue + 1; Session. setattribute ("visitcount", visitcountvalue); Session. setattribute ("idkey", useridvalue); Session. setattribute ("time1", time1); Session. setattribute ("time2", time2); req. getrequestdispatcher ("sessionresult. JSP "). forward (req, resp );}}
Sessionresult. jsp. The foreground uses the El expression to obtain the value within the session range.

<body>    <center>        <p>Session Tracking</p>    </center>    <table border="1" align="center">        <tr bgcolor="#949494">            <th>Session info</th>            <th>Value</th>        </tr>        <tr>            <td>id</td>            <td>${sessionScope.idKey}</td>        </tr>        <tr>            <td>Creation Time</td>            <td>${sessionScope.time1}</td>        </tr>        <tr>            <td>Time of Last Access</td>            <td>${sessionScope.time2}</td>        </tr>        <tr>            <td>Number of visits</td>            <td>                ${sessionScope.visitCount}            </td>        </tr>    </table></body>
The execution result is as follows: every time a page is refreshed, The visitcount of the page is increased by 1.


In-depth analysis and research on httpsession

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.