Server review notes (3) Tomcat and Cookie&Session

Conversational technology

One session: The browser sends a request to the server resource for the first time, and the session is established until one party disconnects.
Session: A session contains multiple requests and responses.
Function: Realize data sharing between multiple requests within the scope of a session
Mode:
1. Client-side session technology: Cookie
2. Server-side session technology: Session

Cookie

Cookie is a client-side session technology that can save data to the client.

Steps for usage

  1. Create Cookie object, bind data
new  Cookie(String name, String value)
  1. Send cookie object
response.addCookie(Cookie cookie)
  1. Get cookies, get data
Cookie[]  request.getCookies() 

Implementation principle

Based on the response header set-cookie and request header cookie implementation, taking two requests as an example, the basic principle can be represented by the following figure:
Insert picture description here

Several questions about cookies

Number of cookie sent in a session

Multiple cookie objects can be created in a session

Cookie validity period

  1. By default, the data in the cookie is destroyed when the browser is closed
  2. Persistent storage
setMaxAge(int seconds)
/*
正数:将Cookie数据写到硬盘文件中。持久化存储,cookie存活时间。
负数: 默认值
零: 删除cookie数据
*/

cookies and Chinese

For tomcat server:
Chinese data cannot be stored directly in cookies before tomcat8. If you want to store Chinese in a cookie, you must re-encode the data-generally URL encoding (%E3) is used to
add cookies

response.setContentType("text/html;charset=utf-8");
String name = URLEncoder.encode("姓名", "UTF-8");
String value = URLEncoder.encode("我爱罗", "UTF-8");
Cookie c = new Cookie(name, value);
c.setMaxAge(3600);
response.addCookie(c);

Get cookies from the client


Cookie[] cs = request.getCookies();
if(cs != null) {
    
    
	for(Cookie c : cs) {
    
    
		String name = URLDecoder.decode(c.getName(), "UTF-8");
        String value = URLDecoder.decode(c.getValue(), "UTF-8");
        String s = name + ": " + value + "<br/>";
        response.getWriter().print(s);
     }
}   

After tomcat8, cookies support Chinese data.

Cookie sharing problem

  1. Assuming that multiple web projects are deployed in a tomcat server, whether these web projects can share cookies with each other.
    Cookie sharing is not possible by default .
  2. How to realize cookie sharing?
    Can pass setPath(String path)
setPath(String path);

Set the scope of cookie acquisition. By default: the sharing scope is the current virtual directory.
If you need the entire server path, you need to set the following directory:

setPath("/");
  1. Cookies sharing between different tomcat servers?
setDomain(String path);

If the first-level domain name is the same, then cookies can be shared between multiple servers

//tieba.baidu.com和news.baidu.com中cookie可以共享
setDomain(".baidu.com");

Characteristics and functions of cookies

  1. Cookies store data in the client browser
  2. The browser has a limit on the size of a single cookie (4Kb), and the total number of cookies under the same domain name is also limited to less than 20.

effect

  1. Cookies are generally used to store small amounts of less sensitive data.
  2. The identification of the customer is performed without the customer logging in the browser.

Case

Remember the time of last visit, basic requirements:

  1. If you visit a Servlet for the first time, you will be prompted: Hello, and welcome your first visit.
  2. If it is not the first visit, the prompt: Welcome back, the time of your last visit is: display the time string.

session

What is session

Session is a server-side session technology that shares data between multiple requests in a session and saves the data in the server-side object HttpSession.

Session steps

  1. Get the HttpSession object:
HttpSession session = request.getSession();
  1. Use the HttpSession object:
Object getAttribute(String name)  
void setAttribute(String name, Object value)
void removeAttribute(String name) 

The principle of session

Graphical session basic principle:
Insert picture description here
The realization of session is dependent on cookie .

Several problems with session

  1. When the client is closed, the server is not closed. Is the same session obtained twice?
    by default. It's not.
    If you need the same, you can create a Cookie, the key is JSESSIONID, set the maximum survival time, and make the cookie persistent.
 Cookie c = new Cookie("JSESSIONID",session.getId());
 c.setMaxAge(60*60);
response.addCookie(c);
  1. The client does not close, after the server is closed, is the same session obtained twice?
    Not the same, but make sure that the data is not lost. Tomcat automatically completes the following work
    session passivation:
    before the server is shut down normally, the session object is serialized to the hard disk (serialization process)
    session activation:
    after the server is started, the session file can be converted into a session object in memory. (Deserialization process).
    Idea has no way to demonstrate session passivation. Demonstrating passivation can only start tomcat directly. From tomcat, you can view the passivation and activation of session .
  2. When is the session destroyed?
    1) Server shutdown
    1. The session object calls invalidate()
      3) The default session invalidation time is 30 minutes.
      web.xml is the parent configuration file of all configuration files, so it can be selectively configured and modified in web.xml
<session-config>
	<session-timeout>30</session-timeout>
 </session-config>

Features of session

  1. session is used to store the data of multiple requests for a session, and it is stored on the server side
  2. Session can store data of any type and size
  3. The difference between session and cookie:
    1) The session stores data on the server side, and the cookie on the client side.
    2) There is no data size limit for session, cookies have.
    3) Session data is safe, cookies are relatively insecure.

Guess you like

Origin blog.csdn.net/xueshanfeitian/article/details/109637521