As well as the principles on the use of Session Session interacting with the browser of all this in the

  
  Said earlier Cookie, Session so why say it? Because the use of Cookie has a very big limitation is that if a lot of Cookie, the intangible increase the amount of data transferred client and service side. And because the browser restrictions on the number of Cookie, destined to too much information and then we can not save the Cookie, so the Session appears.
  Session action is stored in a number of user data server, and then delivered to the user a name for JSESSIONID of cookies, corresponding to the JESSIONID this server a Session object, the user can obtain the Session information stored by it.
Specifically, we look at that Session is what the hell.
  

What is 1. Session

  Session is one of the jsp nine built-in objects. Second Session is a domain object. Session server side is a technique used to store user data. And Session Session is to achieve technology-based Cookie.

  

2.Session use

1.1 Session creation and acquisition

Creating opportunity Session is when request.getSession () method is called first.

  • Added: call (after) request.getSession are acquiring have created Session object.

After the Session is created, while there will be a JSESSIONID called the Cookie is created.
Cookie is the default aging this current session.
[Picture dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-ZaYpcMzu-1575203336945) (Silicon Valley _ still _ Zhang Chunsheng session control .assets / 1558627840672.png)]

Here is the creation and acquisition Session Session. And access to the Session ID number, code samples if Session is newly created:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	public SessionServlet() {
	}

	protected void getSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println(request.getHeader("Cookie"));
		
		// 第一次调用就是创建一个新的Session。如果Session已经创建过。就获取原来的会话。
		HttpSession session = request.getSession();
		// 输出会话id号,和是否是新创建
		// session.getId()返回Session的唯一编号
		// session.isNew()返回当前Session是否是刚创建的
		response.getWriter().write("session ID:" + session.getId() + "<br/>是否是新的:" + session.isNew());
	}
}

In web.xml configuration file:

<servlet>
		<servlet-name>SessionServlet</servlet-name>
		<servlet-class>com.javaWeb.servlet.SessionServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>SessionServlet</servlet-name>
		<url-pattern>/sessionServlet</url-pattern>
	</servlet-mapping>

The first visit of the results:
[Picture dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-t6CEn34K-1575203336945) (Silicon Valley _ still _ Zhang Chunsheng session control .assets / 1558627941430.png)]

After the results of each visit:
[Picture dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-6djJ7kSw-1575203336947) (Silicon Valley _ still _ Zhang Chunsheng session control .assets / 1558627964822.png)]
  

Works 2.2 Session of

  After the Session is created, a corresponding Cookie is saved to the browser after the browser each time you visit the project will carry the Cookie.

  当我们再次调用时会根据该JSESSIONID获取已经存在的Cookie,而不是再创建一个新的Cookie。

  如果Cookie中有JSESSIONID,但是JSESSIONID没有对应的Session存在,则会重新创建一个HttpSession对象,并重新设置JSESSIONID。

[Picture dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-a68FgiGN-1575203336948) (Silicon Valley _ still _ Zhang Chunsheng session control .assets / 1558748151080.png)]

  

2.3 Session数据的存取

Session域对象数据的存取和其他三个域对象PageContext、Request、ServletContext是一样的。只需要调用下面两个方法:

  • setAttribute 设置属性
  • getAttribute 获取属性

编写下面的java代码去访问,就可以在Session域中设置属性,和获取属性。

protected void setAttribute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 第一个调用就是获取一个新的Session。如果Session已经创建过。就获取原来的会话。
		HttpSession session = request.getSession();
		// 设置数据
		session.setAttribute("abc", "abc value");
		response.getWriter().write("设置属性值成功!");
	}
	
	protected void getAttribute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 第一个调用就是获取一个新的Session。如果Session已经创建过。就获取原来的会话。
		HttpSession session = request.getSession();
		// 设置数据
		String value = (String) session.getAttribute("abc");
		response.getWriter().write("获取abc的属性值:" + value);
	}

修改session.html 中访问的连接地址,然后点击访问。

<li>
	<a href="sessionServlet?action=setAttribute" target="target">Session域数据的存储</a>
</li>

<li>
	<a href="sessionServlet?action=getAttribute" target="target">Session域数据的获取</a>
</li>

访问后效果图:
[Picture dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-8Z6I1ahj-1575203336949) (Silicon Valley _ still _ Zhang Chunsheng session control .assets / 1558628097144.png)]
[Picture dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-HV5JguV7-1575203336950) (Silicon Valley _ still _ Zhang Chunsheng session control .assets / 1558628140230.png)]
  

2.4 Session 的有效时间

基本原则:

  Session对象在服务器端不能长期保存,它是有时间限制的,超过一定时间没有被访问过的Session对象就应该释放掉,以节约内存。所以Session的有效时间并不是从创建对象开始计时,到指定时间后释放。而是从最后一次被访问开始计时,统计其“空闲”的时间。

默认时效:

在tomcat的conf目录下web.xml配置文件中能够找到如下配置:

 <!-- ==================== Default Session Configuration ================= -->
   <!-- You can set the default session timeout (in minutes) for all newly   -->
   <!-- created sessions by modifying the value below.                       -->
 
     <session-config>
         <session-timeout>30</session-timeout>
     </session-config>
 

说明:Session对象默认的最长有效时间为30分钟。

手动设置1:全局:

  也可以在自己工程的web.xml文件中配置Session会话的超时时间为10分钟。在web.xml文件中配置的Session会话超时时间是对所有Session都生效的。

<!-- 设置Session默认的过期时间  -->
<session-config>
	<!-- 以分钟为单位。10分钟超时  -->
    <session-timeout>10</session-timeout>
</session-config>

手动设置2:局部:

  • int getMaxInactiveInterval() 获取超时时间。以秒为单位。
  • setMaxInactiveInterval (int seconds) 设置用户多长时间没有操作之后就会Session过期。以秒为单位。
    • 如果是正数。表示用户在给定的时间内没有任意操作,Session会话就会过期。
    • 如果是负数。表示Session永不过期。

强制失效:

  • invalidate()

示例代码:

Session在3秒之后超时
// 第一个调用就是获取一个新的Session。如果Session已经创建过。就获取原来的会话。
HttpSession session = request.getSession();
// 设置过期时间为3秒 
session.setMaxInactiveInterval(3);

Session在1分钟之后超时
// 第一个调用就是获取一个新的Session。如果Session已经创建过。就获取原来的会话。 
HttpSession session = request.getSession();
// 设置过期时间为1分钟
session.setMaxInactiveInterval(60);

Session在1小时之后超时
// 第一个调用就是获取一个新的Session。如果Session已经创建过。就获取原来的会话。
HttpSession session = request.getSession();
// 设置过期时间为1小时
session.setMaxInactiveInterval(60 * 60);

Session在1天之后超时
// 第一个调用就是获取一个新的Session。如果Session已经创建过。就获取原来的会话。
HttpSession session = request.getSession();
// 设置过期时间为1天
session.setMaxInactiveInterval(60 * 60 * 24);

Session在1周之后超时
// 第一个调用就是获取一个新的Session。如果Session已经创建过。就获取原来的会话。
HttpSession session = request.getSession();
// 设置过期时间为1周
session.setMaxInactiveInterval(60 * 60 * 24 * 7);

Session永远不超时
// 第一个调用就是获取一个新的Session。如果Session已经创建过。就获取原来的会话。
HttpSession session = request.getSession();
// 设置永远不超时
session.setMaxInactiveInterval(-1);

Session马上超时(失效)
// 第一个调用就是获取一个新的Session。如果Session已经创建过。就获取原来的会话。
HttpSession session = request.getSession();
// 让Session对象立即过期
session.invalidate();

  

2.4 Session对象的释放
  1. Session对象空闲时间达到了目标设置的最大值,自动释放。
  2. Session对象被强制失效。
  3. Web应用卸载。
  4. 服务器进程停止。

  

2.5 Session的活化和钝化

  Session机制很好的解决了Cookie的不足,但是当访问应用的用户很多时,服务器上就会创建非常多的Session对象,如果不对这些Session对象进行处理,那么在Session失效之前,这些Session一直都会在服务器的内存中存在。那么就,就出现了Session活化和钝化的机制。

Session钝化:Session在一段时间内没有被使用时,会将当前存在的Session对象序列化到磁盘上,而不再占用内存空间。

Session活化:Session被钝化后,服务器再次调用Session对象时,将Session对象由磁盘中加载到内存中使用。

  如果希望Session域中的对象也能够随Session钝化过程一起序列化到磁盘上,则对象的实现类也必须实现java.io.Serializable接口。不仅如此,如果对象中还包含其他对象的引用,则被关联的对象也必须支持序列化,否则会抛出异常:java.io.NotSerializableException。

  

2.6 浏览器和Session关联的技术底层内幕

  In the previous demo, we found that once the browser is closed, we could get a new Session object creates the Session object. This is how it happened. Now look at insider details of the process of this series of operations.
[Picture dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-hJFUXUqO-1575203336951) (Silicon Valley _ still _ Zhang Chunsheng session control .assets / 1558628349795.png)]
  By analyzing the graph, we can easily find. When the browser is closed. Just because the browser no longer Notification Server, Session session id is the number of previously created. After so the server can not find the corresponding Session object, to think that this is the first time to access the server. Creates a new Session object is returned.

  

3.URL rewrite

  Throughout the session control system, Cookie JSESSIONID achieved primarily by maintaining the value. But Cookie may be disabled in the browser, so we also need some spare technical means, such as: URL rewriting.

  URL rewriting is actually the value of a fixed format JSESSIONID attached to the URL address in order to achieve holding JSESSIONID, so as to maintain session state. The fixed format is: URL; jsessionid = xxxxxxxxx

E.g:

targetServlet;jsessionid=F9C893D3E77E3E8329FF6BD9B7A09957

Method to realize:

  • response.encodeURL(String)

  • response.encodeRedirectURL(String)

Example:

//1.获取Session对象
HttpSession session = request.getSession(); 		
//2.创建目标URL地址字符串
String url = "targetServlet";	
//3.在目标URL地址字符串后面附加JSESSIONID的值
url = response.encodeURL(url); 		
//4.重定向到目标资源
response.sendRedirect(url);

Published 166 original articles · won praise 585 · views 60000 +

Guess you like

Origin blog.csdn.net/zxdspaopao/article/details/103718420