day16_Cookie&Session Notes

Keywords: Session Java JSP encoding

Today's Content

1. Session Technology
	1. Cookie
	2. Session
 2. JSP: Getting Started

Session Technology

1. Session: A session contains multiple requests and responses.
	*One session: the first time a browser sends a request to a server resource, the session is established until one of the parties disconnects
 2. Function: Share data between multiple requests within the scope of one session
 3. Mode:
	1. Client Session Technology: Cookie
	2. Server-side Session Technology: Session

Cookie:

1. Concepts: Client-side session technology, saving data to the client

2. Quick Start:
	* Steps to use:
		1. Establish Cookie Object, binding data
			* new Cookie(String name, String value) 
		2. Send out Cookie object
			* response.addCookie(Cookie cookie) 
		3. Obtain Cookie,Get the data
			* Cookie[]  request.getCookies()  


3. Implementation Principle
	* Response Header Based set-cookie And request headers cookie Realization

4. cookie Details
	1. Can't send more than one at a time cookie?
		* Yes?
		* Multiple can be created Cookie Object, using response Multiple calls addCookie Method Send cookie That's it.
	2. cookie How long do I keep it in my browser?
		1. By default, when the browser is closed, Cookie Data destroyed
		2. Persistent storage:
			* setMaxAge(int seconds)
				1. Positive number: will Cookie The data is written to a file on the hard disk.Persist storage.And specify cookie Survival time, after time, cookie Automatic file invalidation
				2. Negative number: default
				3. Zero: Delete cookie information
	3. cookie Can I save it in Chinese?
		* stay tomcat 8 before cookie Chinese data cannot be stored directly in.
			* Chinese data needs to be transcoded---Usually used URL Code(%E3)
		* stay tomcat 8 After that, cookie Support Chinese data.Special characters are not supported, use is recommended URL Coded storage, URL Decode Resolution
	4. cookie Sharing questions?
		1. Assume in one tomcat There are multiple deployments in the server web Projects, then in these web In Project cookie Can you share it?
			* By default cookie Not Sharable

			* setPath(String path):Set up cookie Get range of.By default, set the current virtual directory
				* If you want to share, you can path Set to"/"

		
		2. Different tomcat Interserver cookie Sharing questions?
			* setDomain(String path):If the primary domain name is the same, then between servers cookie Can be shared
				* setDomain(".baidu.com"),that tieba.baidu.com and news.baidu.com in cookie Can be shared
		

5. Cookie Features and Role
	1. cookie Store data in client browser
	2. Browser for single cookie Limited size(4kb) And the total under the same domain name cookie Quantity is also limited(20 individual)

	* Effect:
		1. cookie Typically used to store small amounts of less sensitive data
		2. Complete server-to-client identification without logging on

6. Case Study: Remember Last Visit Time
	1. Requirements:
		1. Access a Servlet,If it's your first visit, hint: Hello, welcome to your first visit.
		2. If this is not your first visit, then Tip: Welcome back, your last visit was:Show time string

	2. Analysis:
		1. Can be adopted Cookie To complete
		2. In Server Servlet Determine if there is a name lastTime Of cookie
			1. Yes: not the first visit
				1. Response data: Welcome back, your last visit was:2018 11 June 10, 2001:50:20
				2. Write Back Cookie: lastTime=2018 11 June 10, 2001:50:01
			2. No: First visit
				1. Response data: Hello, welcome to your first visit
				2. Write Back Cookie: lastTime=2018 11 June 10, 2001:50:01

	3. Code implementation:
		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;
		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 message body of the response
	        response.setContentType("text/html;charset=utf-8");
	
	        //1. Get all cookies
	        Cookie[] cookies = request.getCookies();
	        boolean flag = false;//No cookie is lastTime
	        //2. Traverse the cookie array
	        if(cookies != null && cookies.length > 0){
	            for (Cookie cookie : cookies) {
	                //3. Get the name of the cookie
	                String name = cookie.getName();
	                //4. Determine if the name is: lastTime
	                if("lastTime".equals(name)){
	                    //With this Cookie, it's not your first visit
	
	                    flag = true;//Cookies with lastTime
	
	                    //Set Cookie value
	                    //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 year 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 cookie lifetime
	                    cookie.setMaxAge(60 * 60 * 24 * 30);//One month
	                    response.addCookie(cookie);
	
	
	                    //Response data
	                    //Get the value of the 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 was:"+value+"</h1>");
	
	                    break;
	
	                }
	            }
	        }
	
	
	        if(cookies == null || cookies.length == 0 || flag == false){
	            //No, first visit
	
	            //Set Cookie value
	            //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 year 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 cookie lifetime
	            cookie.setMaxAge(60 * 60 * 24 * 30);//One month
	            response.addCookie(cookie);
	
	            response.getWriter().write("<h1>Hello, welcome to your first visit</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 page
		*Can be understood as a special page that specifies both html tags and java code
		*For simplifying writing!!!


2. Principles
	* JSP is essentially a Servlet

3. JSP scripts: how JSP defines Java code
	1. <%Code%>: Defined java code, in the service method.What can be defined in the service method and what can be defined in the script.
	2. <%! Code%>: Defined java code, in the jsp converted java class member location.
	3. <%=Code%>: Defined java code, which is output to the page.What can be defined in the output statement and what can be defined in the script.


4. JSP's built-in objects:
	*Objects that do not need to be acquired and created in a jsp page and can be used directly
	* There are 9 built-in objects for jsp.
	*Learn 3 today:
		* 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 looks for the response buffer data before the out buffer data.
				* response.getWriter() Data output always precedes out.write()
			
5. Case: Rebuilding Cookie Case

Session: Main course

1. Concepts: Server-side session technology, which shares data between multiple requests in a session and stores the data in server-side objects. HttpSession
2. Quick Start:
	1. Obtain HttpSession Object:
		HttpSession session = request.getSession(); //Get Object
	2. Use HttpSession Object:
		Object getAttribute(String name)  //get data
		void setAttribute(String name, Object value) //Store data
		void removeAttribute(String name)  //Remove Data

3. principle
	* Session Implementation depends on Cookie Of.


4. Details:
	1. When the client shuts down, the server does not shut down, get it twice session Is it the same?
		* By default.No
		* If the same is required, you can create Cookie,The key is JSESSIONID,Set the maximum lifetime to allow cookie Persist save.
			 Cookie c = new Cookie("JSESSIONID",session.getId());
	         c.setMaxAge(60*60);
	         response.addCookie(c);

	2. Client is not shut down, server is shut down, two times get session Is it the same?
		* Not the same, but make sure the data is not lost. tomcat Automatically complete the following tasks
			* session Passivation of:
				* Before the server shuts down normally, the session Serialize Objects to Hard Disk
			* session Activation of:
				* After the server starts, the session Convert files into memory session Object is OK.
			
	3. session When was it destroyed?
		1. Server shutdown
		2. session Object Call invalidate() . 
		3. session Default expiration time of 30 minutes
			//Selective Configuration Modification	
			<session-config>
		        <session-timeout>30</session-timeout>
		    </session-config>

 5. session Features
	 1. session Data used to store multiple requests for a session, on the server side
	 2. session Can store any type, any size of data

	* session and Cookie The difference between:
		1. session Store data on the server side, Cookie On Client
		2. session There is no data size limit. Cookie Yes
		3. session Data security, Cookie Relative to Insecurity

Case: Verification Code

1. Case requirements:
	1. Access login page login.jsp with authentication code
	2. User input username, password and authentication code.
		*If the username and password are entered incorrectly, skip to the login page and prompt: The username or password is incorrect
		*If the Authentication Code is entered incorrectly, skip to the login page, prompt: Authentication Code error
		*If all inputs are correct, jump to the home page success.jsp, showing: User name, welcome


2. Analysis:

Posted by w1ww on Wed, 18 Sep 2019 19:34:49 -0700