Chuanzhi Podcast Web Study Notes 10--Session

Session learning

  1. Session concept: server-side session technology, sharing data between multiple requests in a session, and storing the data in the server-side object.

  2. Session Quick Start:

     1. 获取HttpSession对象:
     	HttpSession session = request.getSession();
     2. 使用HttpSession对象:
     	Object getAttribute(String name)  
     	void setAttribute(String name, Object value)
     	void removeAttribute(String name)  
    
     // 在Session中存、取、删数据
    protected void doGet(HttpServletRequest request,    HttpServletResponse response) throws ServletException,  IOException {
       	//获取Sesseion对象
    	HttpSession session=request.getSession();
    	session.setAttribute("username", "zhangsan");//存储数据
    	session.getAttribute("username");//获取数据
    	session.removeAttribute("username");//删除数据
    }
    
    
    
  3. Session principle

     * Session的实现是依赖于Cookie的。
     * Session是服务器开辟的一个用来存储数据的空间
     * 服务器为每个浏览器单独开辟一个Session
     * 服务器根据浏览器发送过来的Cookie,来确认当前浏览器使用哪个Session
    

In WEB development, the server can create a session object (session object) for each user's browser. Note: a browser monopolizes a session object (by default). Therefore, when user data needs to be saved, the server program can write the user data to the session exclusive to the user's browser. When the user uses the browser to access other programs, the other programs can retrieve the user's data from the user's session. User service.

  1. Session details:

    1. 当客户端关闭后,服务器不关闭,两次获取session是否为同一个?
    	* 默认情况下。不是。
    	* 如果需要相同,则可以创建Cookie,键为JSESSIONID,设置最大存活时间,让cookie持久化保存。
    		 Cookie c = new Cookie("JSESSIONID",session.getId());
             c.setMaxAge(60*60);
             response.addCookie(c);
    
    2. 客户端不关闭,服务器关闭后,两次获取的session是同一个吗?
    	* 不是同一个,但是要确保数据不丢失。tomcat自动完成以下工作
    		* session的钝化:
    			* 在服务器正常关闭之前,将session对象系列化到硬盘上
    		* session的活化:
    			* 在服务器启动后,将session文件转化为内存中的session对象即可。
    		
    3. session什么时候被销毁?
    	1. 服务器关闭
    	2. session对象调用invalidate() 。
    	3. session默认失效时间 30分钟
    		选择性配置修改	
    		<session-config>
    	        <session-timeout>30</session-timeout>
    	    </session-config>
    
  2. Characteristics of session

      1. session用于存储一次会话的多次请求的数据,存在服务器端
      2. session可以存储任意类型,任意大小的数据
    
     * session与Cookie的区别:
     	1. session存储数据在服务器端,Cookie在客户端
     	2. session没有数据大小限制,Cookie有
     	3. session数据安全,Cookie相对于不安全
    
Published 11 original articles · Like1 · Visits 908

Guess you like

Origin blog.csdn.net/Lzy410992/article/details/105673253