Cookie session control, to see which one is enough!

  
  Today to talk about the session cookie control, mainly to talk about the creation of cookie, update, delete, about the principle, and offer a small example for your reference.

1. First to introduce Cookie

1.1 Why do we need Cookie

  HTTP is a stateless protocol, the server can not access the browser's status record, that server can not distinguish between whether to issue two requests by the client. This design has seriously hindered the Web design program. Such as: When we conduct online shopping, buy a pair of pants, bought a cell phone. Since the HTTP protocol is stateless, if not through other means, the server can not know in the end user to buy something. The Cookie is one of the solutions.
  

What is 1.2 Cookie

  Cookie, translation is the meaning of tortillas. It is actually saved on the server browser for some information. After the browser has cookies, sends a request to the server each time are simultaneously transmits the information to the server, the server receives the request, it may request this information processing.

For example: We say above online store, when a user adds a product to the shopping cart, the server sends this message encapsulated in a Cookie sent to the browser, the browser receives Cookie, it will be stored in memory ( Note that memory is native memory rather than server memory), after that each time you send a request to the server, the browser will carry the Cookie, the server can be judged in the end user what to buy merchandise by reading Cookie. When the user performs checkout operation, the server can do the billing information according to the Cookie.

Cookie uses:

  • Online Shopping Mall shopping cart
  • Keep the user logged in

To sum it up: Cookie, is a server tell the browser to a small amount of key-value pairs in the form of technology for storing information.
  

Works of 1.3 Cookie

  Overall Cookie like when the server to the browser of a "membership card", will take this "membership card" Every time the browser sends a request to the server, when the server sees this "membership card" They can identify the identity of the browser.

In fact, this so-called "membership card" is a response sent by the server's head:
[Picture dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-M7CysPeX-1575203336926) (Silicon Valley _ still _ Zhang Chunsheng session control .assets / 1558667076701.png)]
as shown in the Set-Cookie response header is sent to the server in the browser "membership card", is the name of the response header Set-Cookie, behind JSESSIONID = 95A92EC1D7CCB4ADFC24584CB316382E and Path = / Test_cookie, two sets of keys to the server for this information structure is "membership card" setting. Browser receives the information after it will be saved to memory or hard disk.

When a browser sends a request to the server again Cookie will carry this message:

[Picture dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-KKPqDg0n-1575203336927) (Silicon Valley _ still _ Zhang Chunsheng session control .assets / 1558667127766.png)]

This is a request message sent by the browser, in the middle of the painting is red box Cookie information here can be understood as the browser with "membership card" again to access the server.

Thus the server can determine the status of the browser based Cookie information.

Cookie disadvantages:

  • Because Cookie request or response packet, potentially increasing network traffic.
  • Cookie is transmitted differential expressly security.
  • Each browser is limited to Cookie, there are limitations on use.
      

2.Cookie use

2.1 Cookie creation and setting
  1. Cookie objects created in the Servlet, and added to the Response.
  2. Then open the browser to access the Servlet program, the server will send a message to the browser Cookie.
  3. After receiving Cookie browser will be automatically saved, and then we can read the Cookie information when sending the request to the next browser.

Description: Cookie Press F12 to view the content

Cookie creation of graphic:

[Picture dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-GGoBep0S-1575203336929) (Silicon Valley _ still _ Zhang Chunsheng session control .assets / 1558626326421.png)]

Cookie creation of code:

/**
 * Cookie的代码
 */
public class CookieServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	protected void createCookie(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// Cookie的创建
		Cookie cookie = new Cookie("cookie-name", "cookie-Value");
		Cookie cookie2 = new Cookie("cookie-name2", "cookie-Value2");

		// 告诉浏览器保存
		response.addCookie(cookie);
		response.addCookie(cookie2);
		response.getWriter().write("已创建Cookie……");
	}
}

web.xml configuration file

<servlet>
	<servlet-name>CookieServlet</servlet-name>
	<servlet-class>com.javaWeb.servlet.CookieServlet</servlet-class>
</servlet>

<servlet-mapping>
	<servlet-name>CookieServlet</servlet-name>
	<url-pattern>/CookieServlet</url-pattern>
</servlet-mapping>

Modify the access address html page connected to:

<li><a href="CookieServlet?action=createCookie" target="target">Cookie的创建</a></li>

Then click access. Remember, the time of the visit, definitely not the html page into your browser to access care, but the output of the address in the browser, by accessing the Tomcat server to access the page.

Browser Tools - View Results:

Google browser, simply press F12 function key, it will pop up a debugging tool, select the Performance ----- Cookies ---- localhost localhost to view the cookie under the domain name.
[Picture dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-wqeDyxqN-1575203336930) (Silicon Valley _ still _ Zhang Chunsheng session control .assets / 1558626500878.png)]

If the Firefox browser. Also pressing the F12 function key to bring up the debugging tool (be sure to remember to enable all windows). Select Cookies Select card:
[Picture dump outside the chain fails, the source station may have a security chain mechanism, it is recommended to save the pictures uploaded directly down (img-jsevIOFB-1575203336931) (Silicon Valley _ still _ Zhang Chunsheng session control .assets / 1558626536006.png)]
  

2.2 Cookie的读取

读取Cookie主要指读取浏览器中携带的Cookie。

  1. 服务器端获取浏览器传过来的Cookie代码:request.getCookies()
  2. 遍历Cookie数组,获取所有Cookie信息
  3. 修改html连接,点击访问
  4. 打开浏览器工具查看HTTP协议内容
  5. 查看服务器代码获取Cookie后的输出

图解Cookie的获取过程:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XkO6XOQQ-1575203336932)(尚硅谷_张春胜_会话控制.assets/1558626636876.png)]

获取Cookie的代码:

protected void getCookie(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
	// 获取所有cookie对象
	Cookie[] cookies = request.getCookies();
	// 如果没有cookie,则返回null。
	if (cookies != null) {
		// 有cookie则遍历
		for (Cookie cookie : cookies) {
			response.getWriter().write("Cookie名:" + cookie.getName() 
					+ "<br/>Cookie值:" + cookie.getValue() + "<br/><br/>");
		}
	} else {
		response.getWriter().write("没有Cookie");
	}
	
}

修改html页面中的连接访问地址为:

<li><a href="cookieServlet?action=getCookie" target="target">Cookie的获取</a></li>

修改完之后,点击连接访问服务器。

通过浏览器查看请求头:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FTFjgTqh-1575203336933)(尚硅谷_张春胜_会话控制.assets/1558626743021.png)]
页面输出:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-00Ep3WF3-1575203336934)(尚硅谷_张春胜_会话控制.assets/1558626783286.png)]
  

2.3 Cookie值的修改
  1. 在Servlet中添加修改Cookie值的代码

  2. 修改html页面中修改cookie的连接,并访问

  3. 打开浏览器的调试工具查看,请求头和响应头中Cookie的信息

图解修改Cookie值的过程:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KRTPXbq5-1575203336935)(尚硅谷_张春胜_会话控制.assets/1558626892380.png)]

修改Cookie值的代码:

protected void updateCookie(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
	
	// 创建一个已存在key的Cookie对象
	Cookie cookie = new Cookie("cookie-name", null);
	// 修改Cookie的值
	cookie.setValue("this is new value");
	// 通知浏览器保存修改
	response.addCookie(cookie);
	response.getWriter().write("Cookie…已修改值");
}

修改html页面中update修改cookie的访问地址为:

<li><a href="cookieServlet?action=updateCookie" target="target">Cookie值的修改</a>
</li>

修改完Cookie更新的连接访问之后,点击访问。
打开浏览器调试工具查看请求头和响应头中Cookie的信息:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IuXRliJr-1575203336936)(尚硅谷_张春胜_会话控制.assets/1558626979002.png)]

在Resource页签中,查看修改后Cookie的内容:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-T6pROCbf-1575203336937)(尚硅谷_张春胜_会话控制.assets/1558627009024.png)]
  

2.4 Cookie的有效时间

  经过上边的介绍我们已经知道Cookie是存储在浏览器中的,但是可想而知一般情况下浏览器不可能永远保存一个Cookie,一来是占用硬盘空间,再来一个Cookie可能只在某一时刻有用没必要长久保存。所以我们还需要为Cookie设置一个有效时间。

Cookie的实例方法setMaxAge( ) 控制Cookie存活的时间,接收一个int型参数,单位:秒。

  • 参数设置为0,即:setMaxAge(0):立即失效,表示浏览器一收到响应后,就马上删除Cookie,下次浏览器发送请求时,将不会再携带该Cookie。
  • 参数设置大于0:比如setMaxAge(60),表示有效的秒数60秒后,Cookie失效。
  • 参数设置小于0:比如setMaxAge(-1),表示当前会话有效。也就是关闭浏览器后Cookie失效,被删除。
  • 如果不设置失效时间,默认为当前会话有效,一旦关闭浏览器,Cookie就失效,被删除。

图解Cookie过期时间被修改的过程:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cOVpPPAE-1575203336938)(尚硅谷_张春胜_会话控制.assets/1558627416248.png)]

修改Cookie过期时间的代码:

protected void deleteCookie(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
	// 获取Cookie
	Cookie[] cookies = request.getCookies();
	Cookie cookie = null;
	if (cookies != null) {
		// 查找出我们需要修改的Cookie对象
		for (Cookie c : cookies) {
			// 获取键为cookie-name的cookie对象
			if ("cookie-name".equals(c.getName())) {
				cookie = c;
				break;
			}
		}
	}
	if (cookie != null) {
//          负数表示浏览器关闭后删除,正数表示多少秒后删除
//			 设置为零,表示立即删除Cookie
		cookie.setMaxAge(0);
		response.addCookie(cookie);
		response.getWriter().write("删除Cookie……");
	}
	
}

修改html页面中的连接地址:

<li><a href="cookieServlet?action=deleteCookie" target="target">Cookie立即删除</a>
</li>

修改之后,点击访问。

通过浏览器调试工具查看请求响应信息。和Cookie信息:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-p70mVroI-1575203336939)(尚硅谷_张春胜_会话控制.assets/1558627434014.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4AOOV3uC-1575203336941)(尚硅谷_张春胜_会话控制.assets/1558627444677.png)]
  

2.5 Cookie的路径Path设置

  Cookie的路径指告诉浏览器访问哪些地址时应该携带该Cookie,我们知道浏览器会保存很多不同网站的Cookie,比如百度的Cookie,新浪的Cookie,腾讯的Cookie等等。那我们不可能访问百度的时候携带新浪的Cookie,也不可能访问每个网站时都带上所有的Cookie,这是不现实的。所以往往我们还需要为Cookie设置一个Path属性,来告诉浏览器何时携带该Cookie。

我们通过调用Cookie的实例方法setPath(),来设置Cookie的Path路径。这个路径由浏览器来解析。

  • / :代表服务器的根目录
  • 如果设置有效路径为:/abc,则:下面几个路径能访问到Cookie
    • /abc 能获取Cookie
    • /xxxx.xxx 不能获取Cookie
    • /abc/xxx.xxx 能获取Cookie
    • /abc/a/b/c 能获取Cookie
  • 如果不设置,默认会在访问“/项目名”下的资源时携带
    • 如:“/项目名/index.jsp” 、 “/项目名/hello/index.jsp”

设置Cookie对象Path属性的代码:

protected void setPath(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {		
	// 创建一个Cookie对象
	Cookie cookie = new Cookie("cookie-path", "test");
	// 设置Cookie的有效访问路径为/abc/下所有资源
	cookie.setPath(request.getContextPath() + "/abc");
	// 通知浏览器保存修改
	response.addCookie(cookie);
	response.getWriter().write("设置Cookie…的path路径");
}

当我们通过浏览器访问上面的代码,响应头中会有下如下信息:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TQN0PIIA-1575203336942)(尚硅谷_张春胜_会话控制.assets/1558627560065.png)]

下面写一个cookie常用的地方,用户免输入就登录。

需求:第一次登录之后,一个星期内免输入用户名登录。

① 服务器Servlet的代码:

protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求参数
	String userName = request.getParameter("username");
	String password = request.getParameter("password");
	String cb = request.getParameter("cb");
	//
	Cookie cookie=new Cookie("username",userName);
	Cookie cookie2=new Cookie("password",password);
	if("admin".equals(userName)&&"123456".equals(password)) {
		if(cb != null) {
			cookie2.setMaxAge(60*60*24*7);
			cookie.setMaxAge(60*60*24*7);
			response.addCookie(cookie);
			response.addCookie(cookie2);
			response.getWriter().write("<h2>登录成功</h2>");				
		}else {
			cookie2.setMaxAge(0);
			cookie.setMaxAge(0);
			response.addCookie(cookie);
			response.addCookie(cookie2);
			response.getWriter().write("<h2>登录成功</h2>");	
		}
	}else {
		response.sendRedirect(request.getContextPath()+"/login.jsp");
	}
}

② WebContent/login.jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>登录页面</h2>
	<form action="CookieServlet?method=login" method="post">
		用户名:<input name="username" type="text" value="${cookie.username.value }"><br>&emsp;码:<input name="password" type="password" value="${cookie.password.value }"><br>
		要记住密码吗?<input type="checkbox" name="cb" value="cb">
		<input type="submit" value="提交">
	</form>
</body>
</html>

在这里插入图片描述
You can see the page refresh your username and password will be automatically echo after a successful login.
在这里插入图片描述Also can be seen a week later expired.
About the picture of a special cookie does not know we have not found, JSESSIONID the previous presentations, and other specific next speak slightly.

Published 166 original articles · won praise 585 · views 60000 +

Guess you like

Origin blog.csdn.net/zxdspaopao/article/details/103338979