WEB--Cookie&&Session(IDEA version)

Conversational Technology

1. Session: one session contains multiple requests and responses.
	*One session: the browser sends a request to the server resource for the first time, and the session is established until one party disconnects
 2. Function: share data among multiple requests within the scope of one session
 3. way:
	1. Client session Technology: Cookie
	2. Server Session Technology: Session

Modify the methods of doget and dopost in sevlet

Cookie:

1. Concept: client session technology, saving data to client

2. Quick start:
	*Use steps:
		1. Create Cookie object and bind data
			* new Cookie(String name, String value) 
		2. Send Cookie object
			* response.addCookie(Cookie cookie) 
		3. Get cookies and data
			* Cookie[]  request.getCookies()  
/**
 *
 * Cookie quick get start
 *
 */

@WebServlet("/cookieDemo1")
public class CookieDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Create Cookie object
        Cookie c = new Cookie("msg","hello");
        //2. Send cookies
        response.addCookie(c);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

package cn.itcast.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * Cookie quick get start
 *
 */

@WebServlet("/cookieDemo2")
public class CookieDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //3. Get cookies
        Cookie[] cs = request.getCookies();
        //Get data, traverse Cookies
        if(cs != null){
            for (Cookie c : cs) {
                String name = c.getName();
                String value = c.getValue();
                System.out.println(name+":"+value);
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

3. Implementation principle
	*Implementation based on response header set cookie and request header cookie

4. Details of cookies
	1. Can I send multiple cookie s at one time?
		* yes.
		*You can create multiple cookie objects and use response to call addCookie method multiple times to send cookies.
@WebServlet("/cookieDemo3")
public class CookieDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Create Cookie object
        Cookie c1 = new Cookie("msg","hello");
        Cookie c2 = new Cookie("name","zhangsan");
        //2. Send cookies
        response.addCookie(c1);
        response.addCookie(c2);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

	2. How long does the cookie stay in the browser?
		1. By default, when the browser is closed, the Cookie data is destroyed (saved in the memory of the browser)
		2. Persistent storage:
			* setMaxAge(int seconds)
				1. Positive: write cookie data to files on the hard disk. Persistent storage. And specify the cookie survival time. When the time is up, the cookie file will automatically become invalid
				2. Negative: default
				3. Zero: delete cookie information
/**
 *
 * Cookie quick get start
 *
 */

@WebServlet("/cookieDemo4")
public class CookieDemo4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Create Cookie object
        Cookie c1 = new Cookie("msg","setMaxAge");
        //2. Set the lifetime of cookie s
        //c1.setMaxAge(30); / / persist the cookie to the hard disk, and the cookie file will be deleted automatically after 30 seconds
        //c1.setMaxAge(-1);
        //c1.setMaxAge(300);
        c1.setMaxAge(0);//Delete Cookie
        //3. Send cookies
        response.addCookie(c1);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

	3. Can cookies be saved in Chinese?
		*Before tomcat 8, Chinese data cannot be stored directly in cookie s.
			*Need to transcode Chinese data - generally URL code (% E3)
		*After tomcat 8, cookie s support Chinese data. Special characters are not supported. It is recommended to use URL encoding storage and URL decoding resolution
/**
 *
 * Cookie quick get start
 *
 */

@WebServlet("/cookieDemo5")
public class CookieDemo5 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Create Cookie object
        Cookie c1 = new Cookie("msg","Hello");
        //Set path to let all projects deployed under the current server share Cookie information
        c1.setPath("/");

        //3. Send cookies
        response.addCookie(c1);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

	4. cookie sharing?
		1. If there are multiple web projects deployed in a tomcat server, can cookie s be shared in these web projects?
			*Cookies cannot be shared by default

			*setPath(String path): set the scope of cookie acquisition. By default, sets the current virtual directory
				*If you want to share, you can set path to "/"
@WebServlet("/cookieDemo5")
public class CookieDemo5 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Create Cookie object
        Cookie c1 = new Cookie("msg","Hello");
        //Set path to let all projects deployed under the current server share Cookie information
        c1.setPath("/");

        //3. Send cookies
        response.addCookie(c1);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

		2. cookie sharing between different tomcat servers?
			*setDomain(String path): if the primary domain name is the same, cookie s can be shared among multiple servers
				*setDomain(".baidu.com"), then cookie s in tieba.baidu.com and news.baidu.com can be shared
		

5. Characteristics and functions of cookies
	1. The cookie stores data in the client browser (insecure)
	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 (20)

	* role:
		1. Cookies are generally used to store a small amount of less sensitive data
		2. Complete the identification of the server to the client without logging in

JSP: getting started

1. concept:
	*Java Server Pages: java server-side pages
		*It can be understood as: a special page, in which you can specify and define both html tags and java code
		*For simplified writing!!!


2. principle
	*JSP is essentially a Servlet

3. JSP script: how JSP defines Java code
	1. <% code% >: the java code defined in the service method. What can be defined in the service method can be defined in the script.
	2. <%! Code% >: the defined java code, the member position of the Java class after jsp conversion. (generally not defined, which may cause thread safety problems)
	3. <% = code% >: the defined java code will be output to the page. What can be defined in the output statement is what can be defined in the script. (equivalent to output statement)
	4. Cross use between JSP page script and html


4. Built in object of jsp:
*Objects that do not need to be acquired and created in jsp pages and can be used directly
*jsp has nine built-in objects.
*Today I will learn three:
* request
* response
*out: character output stream object. You can output data to a page. Similar to response.getWriter()
*The difference between response.getWriter() and out.write():
*Before the tomcat server actually responds to the client, it will find the response buffer data first, and then the out buffer data.
*response.getWriter() data output always precedes out.write()

Session: main course

1. Concept: server-side session technology, sharing data among multiple requests of a session, and saving the data in the server-side object. HttpSession
2. Quick start:
	1. Obtain HttpSession Participants:
		HttpSession session = request.getSession();
	2. Use HttpSession Participants:
		Object getAttribute(String name)  
		void setAttribute(String name, Object value)
		void removeAttribute(String name)  
@WebServlet("/sessionDemo1")
public class SessionDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Using session to share data

        //1. Get session
        HttpSession session = request.getSession();
        //2. Store data
        session.setAttribute("msg","hello session");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

@WebServlet("/sessionDemo2")
public class SessionDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Using session to get data

        //1. Get session
        HttpSession session = request.getSession();
        //2. Access to data
        Object msg = session.getAttribute("msg");
        System.out.println(msg);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

3. principle
	*The implementation of Session depends on cookies.

4. Details:
	1. When the client is shut down, the server does not shut down, and obtains the session Is it the same?
		* By default. No
		* If you need the same, you can create Cookie,Key is JSESSIONID´╝îSet the maximum survival time to cookie Persistent preservation.
			 Cookie c = new Cookie("JSESSIONID",session.getId());
	         c.setMaxAge(60*60);
	         response.addCookie(c);
@WebServlet("/sessionDemo3")
public class SessionDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1. Get session
        HttpSession session = request.getSession();
        System.out.println(session);


        //It is expected that the session will be the same after the client is shut down
        Cookie c = new Cookie("JSESSIONID",session.getId());
        c.setMaxAge(60*60);
        response.addCookie(c);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

	2. After the client is not shut down and the server is shut down, is the session acquired twice the same?
		*Not the same, but make sure the data is not lost. tomcat does the following automatically
			*Passivation of session:
				*Serialize the session object to the hard disk before the server shuts down normally
			*Activation of session:
				*After the server starts, convert the session file to the session object in memory.
@WebServlet("/sessionDemo3")
public class SessionDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1. Get session
        HttpSession session = request.getSession();
        System.out.println(session);


        //It is expected that the session will be the same after the client is shut down
        Cookie c = new Cookie("JSESSIONID",session.getId());
        c.setMaxAge(60*60);
        response.addCookie(c);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

	3. When is the session destroyed?
		1. Server shutdown
		2. The session object calls invalidate().
		3. Default expiration time of session is 30 minutes
			Selective configuration modification	
			<session-config>
		        <session-timeout>30</session-timeout>
		    </session-config>
@WebServlet("/sessionDemo4")
public class SessionDemo4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1. Get session
        HttpSession session = request.getSession();
        System.out.println(session);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

 5. Characteristics of session
	 1. session is used to store the data of multiple requests of a session, which exists on the server side
	 2. session can store data of any type and size

	*The difference between session and Cookie:
		1. session stores data on the server side and cookies on the client side
		2. session has no data size limit. Cookie s have
		3. session data security, Cookie relative to insecurity
Published 16 original articles, won praise 6, visited 327
Private letter follow

Tags: Session Java JSP Tomcat

Posted on Thu, 12 Mar 2020 07:34:57 -0400 by itarun