5.Servlet of Cookie and Session

A Session

Two technologies:

  • Cookie: Client Technology

  • Session: Server Technology

Common applications: The next time you log in after the website can no longer log in.

1.Cookie

Steps for usage:

  1. Server gets the cookie information from the client

  2. Server settings cookie information back to the client

Cookie Case: server to get and set cookie

 1 public class CookieDemo01 extends HttpServlet {
 2 
 3     @Override
 4     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 5         req.setCharacterEncoding("utf-8");
 6         resp.setCharacterEncoding("utf-8");
 7         resp.setContentType("text/html; charset=utf-8");
 8 
 9         PrintWriter out = resp.getWriter();
10 
11         //服务器从客户端获取cookie
12         Cookie [] = Cookies req.getCookies ();
 13 is  
14          IF (! Cookies = null ) {
 15              out.write ( "your last visit time is:" );
 16  
. 17              for ( int I = 0; I <Cookies .length; I ++ ) {
 18 is                  cookies cookie = cookies [I];
 . 19  
20 is                  // determined name of the cookie 
21 is                  IF . (the Cookie.getName () the equals ( "lastLoginTime" )) {
 22 is                      // Get the value of the cookie 
23 is                      Long lastLoginTime = Long.parseLong (cookie.getValue ());
 24  
25                     = DATE DATE new new DATE (lastLoginTime);
 26 is  
27                      out.write (Date.toLocaleString ());
 28                  }
 29              }
 30          } the else {
 31 is              out.write ( "this is the first visit" );
 32          }
 33 is  
34 is          // the server to the client in response to a cookie 
35          cookies cookie = new new cookies ( "lastLoginTime", System.currentTimeMillis () + "" );
 36  
37 [          // set the cookie is valid for one day 
38 is          cookie.setMaxAge (24 * 60 * 60 );
39         resp.addCookie(cookie);
40     }
41 
42     @Override
43     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
44         doGet(req, resp);
45     }
46 }

cookie commonly used functions:

. 1 cookies [] = req.getCookies Cookies (); // Get cookie 
2 the Cookie.getName ();                    // Get the cookie Key 
. 3 cookie.getValue ();                   // Get the cookie value 
. 4  new new cookies ( "lastLoginTime", System.currentTimeMillis () + ""); // Create a cookie 
5 cookie.setMaxAge (24-* 60 * 60);      // set a cookie valid for 
6 resp.addCookie (cookie);              // browser to return to the client a cookie

Precautions:

  1. A Cookie can only save a message

  2. A web site can send multiple cookie to the browser cookie but store up to 20

  3. Cookie size is limited to 4kb

  4. 300 is the upper limit of the browser cookie

Delete Cookie:

  • Method 1: Do not set the cookie is valid, cookie automatically expire after the browser is closed

  • Method 2: Set the browser is valid for 0

When you delete a cookie, you must first create a cookie to be deleted and have the same key value of the cookie

1  // server to the client in response to a cookie 
2 cookies cookie = new new cookies ( "lastLoginTime", System.currentTimeMillis () + "" );
 . 3  
. 4  // set the cookie is valid for one day 
. 5 cookie.setMaxAge (24 * 60 60 * );
 6 resp.addCookie (the cookie);

For Chinese garbage problem: the use of encoding and decoding

1 cookie = new Cookie("name",URLEncoder.encode("你好!","utf-8"))
2 out.write(URLDecoder.decode(cookie.getValue(),"utf-8"));

2.Session (focus)

(1) What is Session

  • Server will give each user (browser) to create a Session object

  • A session exclusively a browser, as long as the browser is not closed, there has been this Session

  • After the user logs on, the entire site can access the Session (used to store user information, save the information of the shopping cart)

Difference (2) Session and the cookie

  • Cookie: server data stored on the browser, the browser stores, you can create multiple

  • Session: server data stored on the server the user exclusive Session, only a

(3) Session usage scenarios

  • Save a user's login information

  • Save shopping cart information

  • Save frequently used data on the entire site

(4) Use:

SessionDemo01: Get and Set Session

 1 public class SessionDemo01 extends HttpServlet {
 2 
 3     @Override
 4     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 5         //解决中文乱码问题
 6         req.setCharacterEncoding("utf-8");
 7         resp.setCharacterEncoding("utf-8");
 8         resp.setContentType("text/html; charset=utf-8");
 9 
10 
11         //得到Session
12         HttpSession session =the req.getSession ();
 13 is  
14  
15          // Set Session 
16          session.setAttribute ( "name", new new the Person ( "Wang", 24 ));
 . 17  
18 is          // Get the Session ID 
. 19          String sessionId = session.getId ( );
 20 is  
21 is          // determination is not new session 
22 is          IF (session.isNew ()) {
 23 is              resp.getWriter () Write ( "session is successfully created, ID:." + sessionId);
 24          } the else {
 25              RESP. . getWriter () write ( "session already exists in the server, ID:" + sessionId);
 26 is          }
27 
28 
29 
30     }
31 
32     @Override
33     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
34         doGet(req, resp);
35     }
36 }

SessionDemo02: Cross Servlet Access Session

 1 public class SessionDemo02 extends HttpServlet {
 2 
 3     @Override
 4     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 5 
 6         //解决中文乱码问题
 7         req.setCharacterEncoding("utf-8");
 8         resp.setCharacterEncoding("utf-8");
 9         resp.setContentType("text/html; charset=utf-8");
10 
11         //得到Session
12         HttpSession session = req.getSession();
13 
14         Person person = (Person) session.getAttribute("name");
15 
16         resp.getWriter().write("获得person:" + person);
17     }
18 
19     @Override
20     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
21         doGet(req, resp);
22     }
23 }

SessionDemo03: Manually delete the Session

. 1  public  class SessionDemo03 the extends the HttpServlet {
 2  
. 3      @Override
 . 4      protected  void the doGet (the HttpServletRequest REQ, the HttpServletResponse RESP) throws ServletException, IOException {
 . 5          the HttpSession the session = the req.getSession ();
 . 6  
. 7          session.removeAttribute ( "name" );
 . 8  
. 9          // manually unregister Session: Session on that before but it will not create a new log off immediately after Session 
10          session.invalidate ();
 11      }
 12  
13      @Override
 14      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
15         doGet(req, resp);
16     }
17 }

Session may be provided automatically dead time in web.xml

1 <! - Session automatically set to 15 minutes after failure ->
 2 <the session-config>
 . 3    <-the session timeout> 15 </-the session timeout>
 . 4 </ the session-config>

 

Guess you like

Origin www.cnblogs.com/zhihaospace/p/12310376.html