Detailed session and cookie in java

Cookie Overview

 What is Cookie

Cookie translated into Chinese is a small dessert, cookies meaning. In HTTP, it means that the server to the client browser a small dessert. In fact, Cookie is a key and a value constituted, is sent to the server with the response of the client browser. Then the client browser will save up Cookie, next time again to access the server and then the Cookie sent to the server.

 2 Cookie Specification

You can rest assured, Cookie will not fill up your hard drive. Cookie Because a maximum of only 4KB, and the browser can save up to 300 Cookie. Of course, in today's browser wars, some browsers in order to defeat opponents, likely to Cookie specification "extended" some, such as the size of each Cookie is 8KB, can save up to 500 Cookie and so on! But it may fill your hard drive will not appear!
Cookie can not be shared between different browsers! ! !

 3 Cookie role

Cookie's role can be big, but no matter how exaggerated the role of Cookie inseparable from the "tracking client state," this sentence. We know that Cookie information is stored in the server client, then the client will be when the next request in the Cookie back to the server so that the server can identify the client through the information.

Example 2 Cookie is
 Cookie stored to the client
that is part of the response of the work, so this method is the response object. Cookie and the content of the HTTP protocol, it is a method of preservation Cookie HttpServletResponse class.
void addCookie (Cookie c): Cookie object to add the current response object, this method can be called multiple times to complete addition in response to a plurality of objects Cookie.

public class AServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
		Cookie c = new Cookie("name", "renliang");
		response.addCookie(c);
	}
}

Use a browser to access http: // localhost / day06_03 / AServlet , and then see whether the response by HttpWatch the Set-Cookie header information exists header.
  When the re-cross method as http: // localhost / day07_03 / AServlet, whether there is a request to view the header information Cookie header information. Of course, you can try to access http: // localhost / day07_03 / BServlet whether there is a Cookie header in the request header.

Try to access http: // localhost / day07_03 / BServlet , you might say, BServlet does not exist, yes, BServlet was not there, but we only care about the request, do not care about the response. We only need to look at whether there is the Cookie header in the request. You should have tried it, also saw the Cookie request header. This shows that not only will have access AServlet Cookie request header information, but as long as there will be access to this day07_03 Cookie request header.
Cookie size is limited, the browser can save up to 300 Cookie, Cookie a maximum of only 4KB, if you exceed the maximum capacity will be reported as an error.

 server reads the Cookie
we can now save the Cookie to the client, but have not learned how to read the server to Cookie.
If the browser to save the Cookie, so the next time a request is sent to the server into the Cookie request header, then the server needs to read the Cookie in the request. Since it is a read request, then of course it is to use the read request object.
HttpServletRequest: Cookie [] getCookies ()
Note that, it returns a Cookie array, instead of a Cookie object. If the request is not Cookie, then the method returns null.

Cookie[] cs = request.getCookies();
if (cs != null) {
	for (Cookie c : cs) {
		String str = c.getName() + ": " + c.getValue() + "<br/>";
		response.getWriter().print(str);
	}
}

3 Cookie life cycle
Cookie how long it will survive in the client? This is the life of a Cookie. By default, Cookie only survive in the browser's memory, that is, when you close your browser, Cookie will disappear!
You can use Cookie # setMaxAge (int expiry) to set the survival time of Cookie. Cookie expiry parameter represents the number of seconds survival.
 cookie.setMaxAge (60 * 60): indicate the cookie object can survive for 1 hour. Even if you close your browser, even restart the client computer, cookie will survive for 1 hour. Because when maxAge greater than 0, the browser will not only save the cookie in the browser memory, the cookie will be saved to the hard disk.
 cookie.setMaxAge (-1): maxAge default cookie attribute value is 1 (in fact, as long as it is a negative meaning), indicates that only survive in the browser memory. Once you close the browser window, the cookie will disappear.
 cookie.setMaxAge (0): cookie is invalid! It represents the cookie that is not in memory alive, not alive on the hard drive, so the cookie settings only one purpose, which is to cover the client's original cookie, make it void.

4. Browser Cookie Management
The following is a browser to view Cookie test:

C position on the Win7 system IE: \ the Users \ renliang \ AppData \ Local \ in the Microsoft \ Windows \ the Temporary Internet Files
5 Cookie path
Cookie and a path attribute can be set by Cookie # setPath (String) method. You can use HttpWatch see if there is a path Set-Cookie response in. Here is the view Cookie information through FireFox.

In other words, even if you do not set the path Cookie, Cookie is also a path. This path is the path of the request. For example, in the request as http: // localhost / day07_03 / AServlet, the server responds with a Cookie, then the default path is the Cookie / day07_03 /.
For example path of the request is http: // localhost / when day07_03 / servlet / BServlet, the server responds with a Cookie, then the default path is the Cookie / day07_03 / servlet /.

Up to now we have not said what is the use Cookie's path, now let's talk about the role of path. First of all make it clear, path does not mean Cookie path stored in the client! ! ! Path different browsers store Cookie is different! ! ! You can not specify the path Cookie Cookie file storage path! ! !
The path then Cookie is doing it? Assuming your browser is currently already had two Cookie:
l c1: the above mentioned id = name; value = itcast; path = / day07_03 /;
l c2: name = name; value = qdmmy6; path = / day07_03 / the servlet /.

When accessing http: / * When // localhost / day07_03, the request header will contain c1, but will not contain c2.
When accessing http: // localhost / day07_03 / servlet / * , the request header will contain c1 and c2.
That is, when the child access path, the path of his father, Cookie will be included, but when accessing parent path, the path does not include Cookie child.

If you want to set in BServlet of Cookie, when the client access AServlet also included in the request header, then you need to set the path BServlet in Cookie's:
l c2.setPath ( "/ day07_03 /"): a hard-coded;
l c2.setPath (request.getContextpath () + "/ "): live coding.

This will set the path Cookie is stored during a visit AServlet, will be included Cookie BServlet added.

Cookie's SetPath set a cookie path, this path directly to decide whether to request the server loads some cookie from the browser.
First, by default if you do not set a cookie path, the default is a layer of address / name / current path, such as: the request path: / cookie_demo / servlet / login, cookie path: / cookie_demo / servlet
If we set the path, if the current access path contains the cookie path (current access path smaller than the cookie path based on cookie-range) cookie will be loaded into the request object.

6 Cookie saved Chinese
  Cookie saved in Chinese, secondary.
Chinese Cookie is not set, but can be used URLEncodor.encode () method after the encoding is stored in the Cookie. When acquiring Cookie, need to use a method for decoding URLDecoder.decode (), re-use.

Add the response to the client cookies
String name = the URLEncoder.encode ( "name", "UTF-. 8");
String value = the URLEncoder.encode ( "Joe Smith", "UTF-. 8");
cookies cookies new new C = ( name, value);
c.setMaxAge (3600);
response.addCookie ©;

从客户端请求中获取Cookie
response.setContentType(“text/html;charset=utf-8”);
Cookie[] cs = request.getCookies();
if(cs != null) {
for(Cookie c : cs) {
String name = URLDecoder.decode(c.getName(), “UTF-8”);
String value = URLDecoder.decode(c.getValue(), “UTF-8”);
String s = name + ": " + value + “
”;
response.getWriter().print(s);
}
}

**

7. Cookie treatment of disabled

**
default browser cookie is enabled, but in fact we can manually disable the cookie, it is strongly not recommended to disable the cookie

Once banned Cookie spent the vast majority of Internet sites are not logged in, this follow-up to explain to us about the session.
So how are we to judge whether the program through a program cookie on the user's browser is disabled it, is actually very simple, we can just add a cookie to go through, if not to take, indicating that cookie is disabled.
*

Cookie cookie = new Cookie("username", username);
		resp.addCookie(cookie);
		Cookie [] cookies = req.getCookies();
		boolean isExsit = false;
		for(Cookie ck : cookies){
			String name = ck.getName();
			if("username".equals(name)){
				isExsit = true;
			}
		}
		if(!isExsit){
			System.out.println("cookie被禁用了");
		}

HttpSession Overview

 session tracking of the session
the session is one of the object field, which is valid within the range of a session scope. Since it is a domain object session, then of course there should be getAttribute () and setAttribute () methods of the series.
A shared session object within a session, the session can be stored in a data session. Such as the current user's information.
greater than the range of the session request, data can be shared between a plurality of session requests. But the session is less than the range ServletContext (application), session data can not be shared between multiple users.
The current scope of domain objects have learned:

ServletContext > HttpSession > HttpServletRequest

 get the session object
using request.getSession () method can get the session object.
With the session, the session will not have to keep track of the use of Cookie! But the session not as long-lived as Cookie, once the user closes the browser window, then the session is dead.

10 session principle (dependent Cookie)

We all know that HTTP is a stateless protocol, but why session can track the session state? Yes, session-dependent Cookie.
When a client first accesses the server, the server creates a session object for the client, then the session object into session in the pool, in response to the sessionId response to the client by Cookie. Note that only the first visit, the server will create a session, the client response sessionId. Since then would not it!
When the Client Access server again, will bring sessionId in the request to the server, the server session pool sessionId to find the session object, which can be completed session followed. In other words, it is stored in the server-side session object, and the client only sessionId. Every visit is required to match the server-side session object through the client's sessionId! Such user data stored in the session can be used again.
sessionId is sent to the server by a client browser Cookie, the Cookie is maxAge -1, i.e. exists only in the browser memory. If you close all browser windows, then the Cookie will be gone!

11 session failed
session fail for several reasons:
l session.invalidate () method logout session
l session timeout 1 l Cookie is disabled




Published 34 original articles · won praise 6 · views 3672

Guess you like

Origin blog.csdn.net/qq_35986709/article/details/85704378