Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JSP Session


May 12, 2021 JSP


Table of contents


JSP Session

HTTP is a stateless protocol, which means that each time a client retrieves a Web page, a server connection is opened separately, so the server does not record any information requested by the previous client.

There are three ways to maintain a client-server session:


Cookies

The network server can specify a unique session ID as a cookie to represent each client and to identify the client's subsequent requests.

This may not be an effective approach, as many times the browser does not necessarily support cookies, so we do not recommend this approach to maintain the session.


Hide form fields

A web server can send a hidden HTML form field and a unique session ID, as this is:

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

This entry means that when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time a browser sends a request, session_id value can be used to save the tracks of different browsers.

This may be an effective approach, but clicking on hyperlinks in the label does not result in form submission events, so hiding form fields does not support universal session tracking.


Rewrite the URL

You can add some additional data after each URL to distinguish sessions, and the server can associate session identifiers based on that data.

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

Rewriting URLs is a better way to work even if the browser doesn't support cookies, but the disadvantage is that you have to dynamically specify the session ID for each URL, even if it's a simple HTML page.


The session object

In addition to the above methods, JSP uses the HttpSession interface provided by the servlet to identify a user and store all the user's access information.

By default, the JSP allows session tracking, and a new HttpSession object is automatically instantiated for the new client. P rohibiting session tracking requires explicitly turning it off by setting the session property value in the page instruction to false, as follows:

<%@ page session="false" %>

The JSP engine exposes implicit session objects to developers. By providing session objects, developers can easily store or retrieve data.

The following table lists some important ways to session objects:

S.N. Methods and descriptions
1 public Object getAttribute(String name)

Returns an object in the session object that is bound to the specified name and, if not present, null

2 public Enumeration getAttributeNames()

Returns all the object names in the session object

3 public long getCreationTime()

Returns the time the session object was created, in milliseconds, starting in the early hours of January 1, 1970

4 public String getId()

Returns the ID of the session object

5 public long getLastAccessedTime()

Returns the last time the client was accessed, in milliseconds, starting in the early hours of January 1, 1970

6 public int getMaxInactiveInterval()

Returns the maximum interval, in seconds, during which the servlet container keeps the session open

7 public void invalidate()

Invalidate session and untie any objects bound to that session

8 public boolean isNew(

Returns whether the client is a new client, or whether the client refuses to join session

9 public void removeAttribute(String name)

Remove the object with the specified name in the session

10 public void setAttribute(String name, Object value)

Use the specified name and value to produce an object and bind it to the session

11 public void setMaxInactiveInterval(int interval)

Used to specify a time, in seconds, during which the servlet container will keep the session valid


JSP Session app

This example describes how to use the HttpSession object to get the creation time and the last access time. We'll associate a new session object for the request object, if it hasn already exists.

<%@ page import="java.io.*,java.util.*" %>
<%    // 获取session创建时间    Date createTime = new Date(session.getCreationTime());    // 获取最后访问页面的时间    Date lastAccessTime = new Date(session.getLastAccessedTime());     String title = "Welcome Back to my website";    Integer visitCount = new Integer(0);    String visitCountKey = new String("visitCount");    String userIDKey = new String("userID");    String userID = new String("ABCD");     // 检测网页是否由新的访问用户    if (session.isNew()){       title = "Welcome to my website";       session.setAttribute(userIDKey, userID);       session.setAttribute(visitCountKey,  visitCount);    }     visitCount = (Integer)session.getAttribute(visitCountKey);    visitCount = visitCount + 1;    userID = (String)session.getAttribute(userIDKey);    session.setAttribute(visitCountKey,  visitCount); %>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
<table border="1" align="center"> 
<tr bgcolor="#949494">
   <th>Session info</th>
   <th>Value</th>
</tr> 
<tr>
   <td>id</td>
   <td><% out.print( session.getId()); %></td>
</tr> 
<tr>
   <td>Creation Time</td>
   <td><% out.print(createTime); %></td>
</tr> 
<tr>
   <td>Time of Last Access</td>
   <td><% out.print(lastAccessTime); %></td>
</tr> 
<tr>
   <td>User ID</td>
   <td><% out.print(userID); %></td>
</tr> 
<tr>
   <td>Number of visits</td>
   <td><% out.print(visitCount); %></td>
</tr> 
</table> 
</body>
</html>

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

JSP Session

Visit again and you'll get the following results:

JSP Session


Delete Thession data

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

  • Remove a specific property:

    Call the public void removeAttribute method to remove the specified property.

  • Delete the entire session:

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

  • Set the session expiration date:

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

  • Post a user:

    Servers that support the servlet 2.4 version can call the logout() method to log out the user and invalidate all relevant sessions.

  • Configure the .xml files:

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

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

The timeout is in minutes, and the default timeout in Tomcat is 30 minutes.

The getMaxInactiveInterval() method in Servlet returns a timeout in seconds. If 15 .xml configured in the web, the getMaxInactiveInterval() method returns 900.