Today’s content

Session technique 1. Cookie 2. Session 2. JSP: Getting startedCopy the code

Session technology

1. Session: A session contains multiple requests and responses. * Session: the first time a browser sends a request to a server resource, a session is established until one party disconnects. 2. Run the following command to share data between multiple requests within the scope of a session: Client Session technology: Cookie 2. Server Session technology: SessionCopy the code

Cookies:

1. Concept: client session technology, save data to client 2. Quick start: * * new Cookie(String name, String Value) 2. Response.addcookie (Cookie Cookie) 3. * Cookie[] request.getcookies () 3. Implementation principle * Based on the response header set-cookie and request header cookie implementation 4. Can I send multiple cookies at a time? * You can create multiple Cookie objects by calling the addCookie method multiple times in Response. 2. How long does the cookie stay in the browser? 1. By default, when the browser is closed, the Cookie data is destroyed. * setMaxAge(int seconds) 1. Positive: Writes Cookie data to a file on the hard disk. Persistent storage. And specify the cookie survival time, when the time expires, the cookie file automatically becomes invalid. 2. Negative: default value 3. Zero: delete cookie information 3. * Before Tomcat 8, Chinese data could not be stored directly in cookies. * Need to transcode Chinese data -- generally using URL encoding (%E3) * After Tomcat 8, cookies support Chinese data. Special characters are still not supported. You are advised to use URL encoding for storage and URL decoding and parsing. 4. 1. Suppose there are multiple Web projects deployed on a Tomcat server. Can cookies be shared among these Web projects? * By default, cookies cannot be shared. * setPath(String path): Sets the scope of the cookie. By default, set the current virtual directory * If you want to share, you can set the path to "/" 2. Cookie sharing problem between different Tomcat servers? * setDomain(String path): If the first level domain is set to the same, So multiple servers can share cookie * setDomain(".baidu.com"), so cookies in tieba.baidu.com and news.baidu.com can share cookie 5. Cookie stores data in client browser 2. The browser has limits on the size of a single cookie (4KB) and the total number of cookies in the same domain (20). The server identifies the client without logging in 6. Case: Remember the last access time 1. 1. Access a Servlet, if this is the first time to access, the prompt: Hello, welcome to visit for the first time. 2. If it is not the first time to access, the prompt: Welcome back, you last accessed the time is: display time string 2. The Servlet in the server determines whether there is a Cookie named lastTime. 1. There are: not first access 1. Response data: Welcome back, you last accessed: June 10, 2018 11:50:20 2. Write back to Cookie: lastTime= jun 10, 2018 11:50:01 2. 1. Response data: Hello, welcome to your first visit 2. Write back to Cookie: lastTime= jun 10, 2018 11:50:01 3. 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 of the response body and encode response.setContentType("text/ HTML; charset=utf-8"); 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. String name = cookie.getName(); // check whether the name is: lastTime if("lastTime".equals(name)){// There is this Cookie, not the first access flag = true; Date = new Date(); Date = new Date(); Date = new Date(); SimpleDateFormat SDF = new SimpleDateFormat(" YYYY yyyy MM dd HH: MM :ss"); String str_date = sdf.format(date); System.out.println(" before encoding: "+str_date); Str_date = URLEncoder. Encode (str_date," utF-8 "); System.out.println(" after encoding: "+str_date); cookie.setValue(str_date); Cookie. setMaxAge(60 * 60 * 24 * 30); Response.addcookie (cookie); String value = cookie.getValue(); String value = cookie.getValue(); System.out.println(" before decoding: "+value); //URL decode: value = urldecoder. decode(value," utF-8 "); System.out.println(" decode: "+value); Response.getwriter ().write("<h1> welcome back, you last visit time :"+value+"</h1>"); break; }}} the if (cookies = = null | | cookies, length = = 0 | | flag = = false) {/ / no, for the first time to visit / / set the value of the Cookie string / / get the current time, Cookie Date = new Date(); SimpleDateFormat SDF = new SimpleDateFormat(" YYYY yyyy MM dd HH: MM :ss"); String str_date = sdf.format(date); System.out.println(" before encoding: "+str_date); Str_date = URLEncoder. Encode (str_date," utF-8 "); System.out.println(" after encoding: "+str_date); Cookie cookie = new Cookie("lastTime",str_date); Cookie. setMaxAge(60 * 60 * 24 * 30); 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); }}Copy the code

JSP: Getting started

Java Server Pages is a special page that allows you to define both HTML tags and Java code to simplify writing. JSP script: how JSP defines Java code 1. <% code %> : Defines Java code, in the Service method. Whatever can be defined in the service method can be defined in this script. 2. < %! Code %> : Java code defined at the member position of the Java class after JSP transformation. 3. <%= code %> : Defined Java code, output to the page. Whatever can be defined in the output statement can be defined in the script. 4. JSP built-in objects: * Objects that do not need to be retrieved and created in JSP pages, but can be used directly * JSP has a total of nine built-in objects. * Request * Response * out: character output stream object. You can output data to a page. Similar to Response.getwriter () * Difference between Response.getwriter () and out.write() : * Before the Tomcat server actually responds to the client, it looks for the response buffer data first and then for the out buffer data. * Response.getwriter () data output is always before out.write() 5. Case: Transform Cookie caseCopy the code

The Session: the main course

1. Concept: Server-side session technology, in which data is shared between multiple requests for a session and stored in objects on the server side. Session = request.getSession(); HttpSession = request.getSession(); 2. Use the HttpSession object:  Object getAttribute(String name) void setAttribute(String name, Object value) void removeAttribute(String name) 3. Principles * Session implementation is dependent on cookies. 4. Details: 1. If the client is closed but the server is not closed, is the session obtained twice the same? * By default. It isn't. * If you need to be the same, you can create a Cookie, key JSESSIONID, set the maximum lifetime, let the Cookie persistent. Cookie c = new Cookie("JSESSIONID",session.getId()); c.setMaxAge(60*60); response.addCookie(c); 2. The client is not shut down. After the server is shut down, is the session obtained twice the same? * Not the same, but make sure the data is not lost. Tomcat does the following automatically * Session passivation: * Serialize session objects to hard disk before normal server shutdown * Session activation: * Convert session files to in-memory session objects after server startup. 3. When is the session destroyed? 2. The session object calls invalidate(). 3. Default session expiration time 30 minutes Optional configuration modification <session-config> <session-timeout>30</session-timeout> </session-config> 5. Session is used to store the data of multiple requests for a session, which exists on the server side. 2. Session can store data of any type and size * The difference between session and Cookie: Session stores data on the server and cookies on the client. 2. There is no limit on the size of session data, but cookies have securityCopy the code

Case study: Captcha

1. Case requirements: 1. Access the login page login.jsp with the verification code 2. The user enters the user name, password, and verification code. * If the user name and password are incorrect, jump to the login page, prompt: User name or password is incorrect * If the verification code is incorrect, jump to the login page, prompt: Verification code is incorrect * If all the input is correct, jump to the home page success.jsp, display: user name, welcome you 2. Analysis:Copy the code