day10_Cookie&Session

Today's content

1. Session technology 
    1. Cookie 
    2. Session 
2. JSP: introductory learning

 

Conversational technology

1. Session: A 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 between multiple requests within the scope of one session. 
3. Method: 
    1. Client Session technology: Cookie 
    2. Server-side session technology: Session

Cookie:

1. Concept: client session technology to save data to the client 
2. Quick Start: 
    * Use these steps: 
        1. Create a Cookie object, bind data 
            * new new Cookie (String name, String value) 
        2. Send Cookie object 
            * response.addCookie (Cookie cookie) 
        3. Get the cookie and get the data 
            * Cookie [] request.getCookies ()  
3. The principle 
    * Based on the response headers and request headers set-cookie cookie achieve 
4. cookie details 
    1. Can you send more than one cookie? 
        * Can 
        * Cookie can create multiple objects, use the response method to send multiple calls addCookie Cookie is enough. 
    2. How long do cookies stay in the browser? 
        1. By default, when the browser is closed, the cookie data is destroyed 
        . 2. Persistent storage: 
            * setMaxAge (int seconds) 
                1. Positive number: Write the cookie data to a file on the hard disk. Persistent storage. And specify the cookie survival time, after the time expires, the cookie file automatically expires 
                2. Negative number: the default value 
                3. Zero: delete cookie information 
    3. Can the cookie be stored in Chinese? 
        * Before tomcat 8, cookies cannot directly store Chinese data. 
            * Need to transcode Chinese data --- generally URL encoding (% E3) 
        * After tomcat 8, cookies support Chinese data. Special characters are still not supported, it is recommended to use URL encoding storage, URL decoding analysis 
    4. Cookie sharing issues?
        1. Assuming that multiple web projects are deployed in a tomcat server, can cookies be shared among these web projects? 
            * Cookie by default can not be shared 
            * setPath (String path): set a cookie acquisition range. By default, set the current virtual directory 
                * If you want to share, you can set the path to "/"

2. The problem of cookie sharing between different tomcat servers? * setDomain (String path): If the first-level domain name is set the same, cookies can be shared between multiple servers * setDomain (". baidu.com"), then cookies in tieba.baidu.com and news.baidu.com can be shared

5. Cookie features and functions 
    1. cookie data stored in the client browser 
    2. The browser limited (4KB) for a single size of a cookie, and there are limits on the total amount of a cookie in the same domain (20) 
    * action : 
        1. the cookie used to store a small amount of generally less sensitive data 
        2. without login, complete identification of the client server 
6. case: Remember the last access time 
    1. requirements: 
        1. visit A Servlet, if it is the first visit, then prompt: Hello, welcome to visit for the first time. 
        2. If it is not the first visit, the prompt: Welcome back, your last visit time: displays the time string 
    2. Analysis: 
        1. Cookie can be accomplished using 
        2. Servlet in the server to determine whether there is a name Cookie for lastTime 
            1. Yes : Not the first visit 
                1. Response data: Welcome back, your last visit time is: 11:50:20, June 10, 2018 
                2. Write back the cookie: lastTime = 2018 6 11:50:01 on October 10 
            2. No: it is the first visit
                1. Response data: Hello, welcome to your first visit 
                2. Write back Cookie: lastTime = 2018 Nian 6 Yue 10 Ri 11:50:01 
    3. Code to achieve: 
        Package Penalty for cn.hou.cookie; 
        Import the 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; 
        import java.net.URLDecoder; 
        import java.net.URLEncoder; 
        import java.text.SimpleDateFormat; 
        import java.util.Date;
    @WebServlet ("/ cookieTest") 
    public class CookieTest extends HttpServlet { 
        protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
            // Set the data format and encoding of the 
            response message body response.setContentType ("text / html; charset = utf-8 "); 
    
            // 1. Get all cookies 
            Cookie [] cookies = request.getCookies (); 
            boolean flag = false; // No cookie is lastTime 
            // 2. Traverse cookie array 
            if (cookies! = null && cookies.length> 0) { 
                for (Cookie cookie: cookies) { 
                    // 3. Get the cookie name 
                    String name = cookie.getName ();
                    // 4. Determine if the name is: lastTime 
                    if ("lastTime" .equals (name)) { 
                        // With this cookie, not the first time to visit 
    
                        flag = true; // With lastTime cookie 
    
                        // Set the value of cookie 
                        / / Get the string of the current time, reset the cookie value, and resend the cookie 
                        Date date = new Date (); 
                        SimpleDateFormat sdf = new SimpleDateFormat ("yyyy MM month dd day HH: mm: ss"); 
                        String str_date = sdf .format (date); 
                        System.out.println ("Before encoding:" + str_date); 
                        // URL encoding 
                        str_date = URLEncoder.encode (str_date, "utf-8");
                        System.out.println ("After encoding:" + str_date);  
                        cookie.setValue (str_date);
                        // Set the cookie survival time 
                        cookie.setMaxAge (60 * 60 * 24 * 30); // One month 
                        response.addCookie (cookie);

// Response data // Get the value of Cookie, time String value = cookie.getValue (); System.out.println ("Before decoding:" + value); // URL decoding: value = URLDecoder.decode (value, " utf-8 "); System.out.println (" After decoding: "+ value); response.getWriter (). write (" <h1> Welcome back, your last visit time is: "+ value +" </ h1 > ");

                        break;
    
                    }
                }
            }

if (cookies == null || cookies.length == 0 || flag == false) {// No, first visit

                // Set the value of the cookie 
                // Get the string of the current time, reset the value of the cookie, and resend the cookie 
                Date date = new Date (); 
                SimpleDateFormat sdf = new SimpleDateFormat ("yyyy MM month dd day HH: mm: ss "); 
                String str_date = sdf.format (date); 
                System.out.println (" Before encoding: "+ str_date); 
                // URL encoding 
                str_date = URLEncoder.encode (str_date," utf-8 "); 
                System.out .println ("after encoding:" + str_date); 
    
                Cookie cookie = new Cookie ("lastTime", str_date); 
                // Set the cookie lifetime 
                cookie.setMaxAge (60 * 60 * 24 * 30); // One month 
                response .addCookie (cookie);
    
                response.getWriter (). write ("<h1> Hello, you are welcome to visit for the first time </ h1>"); 
            }

}

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

JSP: Getting started

1. Concepts: 
	* Java Server Pages: java server-side pages 
		* can be understood as: a special page in which you can specify the definition of html tags, you can also define java code 
		* used to simplify writing! ! !
2. Principle 
	* JSP is essentially a Servlet 

3. JSP script: the way JSP defines Java code 
	1. <% code%>: The defined java code is in the service method. What can be defined in the service method, what can be defined in the script. 
	2. <%! Code%>: the defined java code, the member position of the java class after jsp conversion. 
	3. <% = code%>: The defined java code will be output on the page. What can be defined in the output statement, what can be defined in the script.
4. Built-in objects of JSP: 
	* Objects that can be used directly without getting and creating in jsp pages 
	* There are 9 built-in objects in jsp. 
	* Learn 3 today: 
		* request 
		* response 
		* out: character output stream object. Data can be output to the page. Similar to response.getWriter () 
			* The difference between response.getWriter () and out.write (): 
				* Before the tomcat server actually responds to the client, it will first find the response buffer data and then the out buffer data. 
				* response.getWriter () data output will always be before out.write () 
			
5. Case: Transforming Cookie Case

 

Session: Main course

1. Concept: server-side session technology, sharing data between multiple requests in a session and storing the data in objects on the server side HttpSession 
2. Quick start: 
	1. Get HttpSession object: 
		HttpSession session = request.getSession (); 
	2. Use HttpSession object: 
		Object getAttribute (String name)   
		void setAttribute (String name, Object value) 
		void removeAttribute (String name)   

3. Principle 
	* Session implementation is dependent on cookies.

4. Details: 1. When the client is closed, the server is not closed. Is the same session obtained twice? * by default. No. * 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);

	2. The client does not shut down. After the server shuts down, is the same session obtained twice? 
		* Not the same, but make sure that the data is not lost. tomcat automatically completes the following tasks 
			* session passivation: 
				* serialize the session object to the hard disk before the server is shut down normally 
			* session activation: 
				* after the server starts, convert the session file into a session object in memory. 
			
	3. When is the session destroyed? 
		1. The server shuts down 
		2. The session object calls invalidate (). 
		3. The default expiration time of session is 30 minutes. 
			Selective configuration modification	 
			<session-config> 
		        <session-timeout> 30 </ session-timeout> 
		    </ session-config> 

 5. Features of 
	 session 1. session is used to store more than one session The requested data exists on the server side 
	 . 2. The session can store any type of data of any size. 

	* 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 the session. Cookies have 
		3. Session data is safe, cookies are relatively insecure

Case: verification code

1. Case requirements: 
	1. Access the login page login.jsp with a verification code 
	2. The user enters the user name, password and verification code. 
		* If the user name and password are entered incorrectly, jump to the login page, prompting: the user name or password is incorrect 
		* If the verification code is entered incorrectly, jump to the login page, prompting: the verification code is incorrect 
		* If all entries are correct, jump to the home page success.jsp, display: username, welcome you
2. Analysis:

 

Published 43 original articles · praised 0 · visits 1070

Guess you like

Origin blog.csdn.net/aaa_56234/article/details/105673690