Latest web development tutorials

JSP Session

HTTP is a stateless protocol, which means that each time a client retrieves pages, must open a separate connection server, the server does not record the previous client requests any information.

There are three ways to keep client and server sessions:


Cookies

Network server may assign a unique session ID as a cookie to represent each client to identify the client's next request.

This may not be an efficient way, because a lot of times do not necessarily support the browser cookie, so we do not recommend using this method to maintain session.


Hidden form fields

A web server can send a hidden HTML form fields and a unique session ID, like this:

<input type="hidden" name="sessionid" value="12345">

This entry means that when the form is submitted, the specified name and value will be automatically included in GET or POST data. Whenever the browser sends a request, the session_id value can be used to save different browser trajectory.

This approach may be an effective way, but does not produce a form submission event Click <A HREF> tab hyperlink, and therefore hidden form fields do not support generic session tracking.


URL rewriting

You can add some extra data behind each URL to distinguish the session, according to the data server can be associated session identifier.

For example, http: //w3cschool.cc/file.htm; sessionid = 12345, session identifier sessionid = 12345, the server can use this data to identify the client.

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


session objects

In addition to the above several methods outside, JSP servlet HttpSession interface provides use to identify a user, to store all the user's access to information.

By default, JSP allows the session tracking, a new HttpSession object will automatically for new client instantiated. Prohibition session tracking needs to explicitly turn it off by the page directive session attribute value to false to achieve, as follows:

<%@ page session="false" %>

JSP engine implicit session object is exposed to the developer. By providing a session object, developers can easily store or retrieve data.

The following table lists some of the important ways session object:

SN Method & description
1 public Object getAttribute (String name)

The returned object session object bound with the specified name, or null if none exist
2 public Enumeration getAttributeNames ()

Returns the session object all object names
3 public long getCreationTime ()

Returns the session object is created time, in milliseconds, from 1 January 1970 the date of the early morning
4 public String getId ()

Returns the session object ID
5 public long getLastAccessedTime ()

Returns the last time the client visited, in milliseconds, from 1 January 1970 the date of the early morning
6 public int getMaxInactiveInterval ()

Returns the maximum time interval, in seconds, servlet container will keep the session open at this time
7 public void invalidate ()

The session invalidation, unbundling any objects bound to the session
8 public boolean isNew (

Returns whether a new client, or if the client refused to join the session
9 public void removeAttribute (String name)

Remove the specified session object name
10 public void setAttribute (String name, Object value)

To produce an object with the specified name and value and bound to the session
11 public void setMaxInactiveInterval (int interval)

To specify the time, in seconds, servlet container will keep the session valid during this period

JSP Session Application

This example describes how to use the HttpSession object to obtain the creation time and last access time. We will be a new session object for the associated request object, if this object does not already exist.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*" %>
<%
   // 获取session创建时间
   Date createTime = new Date(session.getCreationTime());
   // 获取最后访问页面的时间
   Date lastAccessTime = new Date(session.getLastAccessedTime());

   String title = "再次访问本教程实例";
   Integer visitCount = new Integer(0);
   String visitCountKey = new String("visitCount");
   String userIDKey = new String("userID");
   String userID = new String("ABCD");

   // 检测网页是否由新的访问用户
   if (session.isNew()){
      title = "访问本教程实例";
      session.setAttribute(userIDKey, userID);
      session.setAttribute(visitCountKey,  visitCount);
   } else {
	   visitCount = (Integer)session.getAttribute(visitCountKey);
	   visitCount += 1;
	   userID = (String)session.getAttribute(userIDKey);
	   session.setAttribute(visitCountKey,  visitCount);
   }
%>
<html>
<head>
<title>Session 跟踪</title>
</head>
<body>

<h1>Session 跟踪</h1>

<table border="1" align="center"> 
<tr bgcolor="#949494">
   <th>Session 信息</th>
   <th>值</th>
</tr> 
<tr>
   <td>id</td>
   <td><% out.print( session.getId()); %></td>
</tr> 
<tr>
   <td>创建时间</td>
   <td><% out.print(createTime); %></td>
</tr> 
<tr>
   <td>最后访问时间</td>
   <td><% out.print(lastAccessTime); %></td>
</tr> 
<tr>
   <td>用户 ID</td>
   <td><% out.print(userID); %></td>
</tr> 
<tr>
   <td>访问次数</td>
   <td><% out.print(visitCount); %></td>
</tr> 
</table> 
</body>
</html>

Try to access http: // localhost: 8080 / testjsp / main.jsp, first run will get the following results:

Visit again, we will get the following results:


Delete Session Data

When finished processing a user's session data, you have the following options:

  • Remove a specific property:

    Call public void removeAttribute (String name) method to remove the specified property.

  • To delete an entire conversation:

    Call public void invalidate () method to make the entire session is invalid.

  • Setting Session Duration:

    Call public void setMaxInactiveInterval (int interval) method to set the session timeout.

  • Sign User:

    Servlet2.4 supported versions of the server, you can call logout () method to log out the user and all associated session is invalid.

  • Web.xml configuration file:

    If you are using Tomcat, you can configure web.xml file to the following:

  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>

Time-out in minutes, Tomcat default timeout is 30 minutes.

Servlet in getMaxInactiveInterval () method returns the timeout seconds. If the web.xml is configured for 15 minutes, then getMaxInactiveInterval () method will return 900.