Summary of session Object in java and Its Common Methods

  • 2021-10-24 22:43:09
  • OfStack

The session object is used to record the access status of each client within the session scope, so that it is easy to track the operation status of each client, and the information stored in the session can obtain the valid data of these sessions when the browser makes subsequent requests.

In the jsp page, you can use the session object directly (built-in object of jsp), or you can go back to the session object through pageContext. getSession () or request. getSession.

session can save user information and implement shopping cart and other functions.

HTTP protocol is a stateless protocol, Request from client to server request, Then the server returns the response response, and the connection is closed. The server does not save the relevant information of the connection. Therefore, when the next connection is made, the server has no previous connection information, and it is impossible to judge that the connection and the previous connection are the same as the customer information. Therefore, the session must be used to record the information about the connection.

From the time the client opens the browser to connect to the server, to the time the client closes the browser and leaves the server, it is called a session. When a client accesses the server, it may repeatedly connect several pages on this server, refresh one page repeatedly or submit information to one page continuously, etc. The server should know that this is the same client in some way, and then the session object is needed.

session works as follows:

1. When a client accesses a page of the server for the first time, the server will assign an session object to the user, specify an ID with only 1 for this session, and send the ID to the client and write it into cookie, so that the client and the session of the server establish an 11-corresponding relationship;

2. When the client continues to access other resources on the server side, the server will not allocate new session objects to the client until the client browser closes, timeout or invokes invalidate () method of session to invalidate it, and the session between the client and the server ends.

3. When the client reopens the browser to visit the website, the server will reassign an session object to the client and reassign sessionID.

session objects are mainly used for attribute manipulation and session management. Common methods are as follows:

1. public void setAttribute(String name,String value) Sets the value of the property with the specified name, adds it to the session session scope, and changes the value of the property if it exists in session scope.

2. public Object getAttribute(String name) Gets the value of the property with the specified name in session scope, returning object or null if the property does not exist.

3. public void removeAttribute(String name) Deletes the session property with the specified name, and an exception occurs if the property does not exist.

4. public void invalidate() , invalidating the session. You can invalidate the current session immediately, and all objects stored in the original session can no longer be accessed.

5. public String getId( ) Gets the current session ID. Each session has a one-only label sessionID on the server side, and the one-only data sent by session object to browser is sessionID, which is generally stored in cookie.

6. public void setMaxInactiveInterval(int interval) Sets the maximum duration of a session in seconds, and a negative number indicates that the session never fails.

7. public int getMaxInActiveInterval() Gets the maximum duration of the session.

8. The getCreationTime () and getLastAccessedTime () methods of the session object can be used to get the time of session creation and the time of last access, but the return value is milliseconds, so the following transformation is needed to get the specific date and time.


Date creationTime = new Date(session.getCreationTime());
Date accessedTime = new Date(session.getLastAccessedTime());

<%@ page language="java" import="java.util.*" contentType="text/html;charset=GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>" rel="external nofollow" >   
    <title>session Object method </title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" >
 -->
  </head>
 
  <body>
    <b>
     Conversation ID : <%=session.getId() %> <br>
     New session or not: <%=session.isNew() %><br>
     Setting and Getting Property Objects: User Name  =
    <%session.setAttribute(" User name ","bing"); %>
    <%=session.getAttribute(" User name ") %><br>
    <%
    Date creationTime = new Date(session.getCreationTime());
    Date accessedTime = new Date(session.getLastAccessedTime());
     %>
      Session creation time: <%=creationTime %><br>
      Last visited: <%=accessedTime %><br>
      Session duration ( s ): <%=session.getMaxInactiveInterval() %><br>
     <%session.setMaxInactiveInterval(12); %>
      Modified session duration ( s ): <%=session.getMaxInactiveInterval() %><br>
     <%session.invalidate(); %>
     </b>
  </body>
</html>

Several methods commonly used to obtain session

1. In spring mvc


HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

2. In struts2

(1)


ActionContext context = ActionContext.getContext(); 
Map request = (Map) context.get("request"); 
Map session = context.getSession(); 
Map application = context.getApplication(); 

(2)


ActionContext actionContext = ActionContext.getContext(); 
HttpServletRequest request = (HttpServletRequest) actionContext
.get(ServletActionContext.HTTP_REQUEST); 
HttpSession session = request.getSession(); 
ServletContext context = (ServletContext) actionContext 
 .get(ServletActionContext.SERVLET_CONTEXT); 

3. Get through ServletActionContext


HttpServletRequest request = ServletActionContext.getRequest(); 
HttpSession session = request.getSession(); 

Related articles: