1. What is a cookie? Baidu's netizens' comments
Simply put, a cookie is a piece of information temporarily stored on your computer by the server so that the server can use it to identify your computer. When you are browsing a website, the web server will first send a small amount of information to put it on your computer. When you visit the same website next time, the web server will first check if there is any cookie information it left behind last time. If so, the user will be judged based on the content in the cookie and send you specific web page content.
2. Where are cookies?
3. Can cookies be deleted?
4. Cookie implementation principle
The first time I request the browser, in the browser's cookie store, there are no cookies,
The first visit does not contain cookies. The browser adds a cookie request header to the Http request message to pass the cookie back to the web server. The browser will store the information fragment of the cookie in the form of "name/value" pairs (name-value pairs). The next time you access, the web server adds a Set-Cookie response header to the http response message to send the cookie information to the browser.
Let's take a look at the cookies by reality
Create a cookie.jsp, set session="false" for easy observation
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8" session="false"%><!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><%//Create a cookieCookie Cookie = new Cookie("name","wyf");response.addCookie(cookie);%></body></html>We first access the cookie.jsp file, enter it in IE
http://localhost:8080/day01/cookie.jsp
In the request header, you can see that the first visit does not carry cookies.
In the response header, it is sent back through Set-Cookie and saved in the browser's local cookie store
We access the cook.jsp file for the second time to see if there is any change
In the request header, you can see that access is a request that carries cookies from the local cookie storage area of the browser.
The following is the response header:
Let’s use an interactive graph to understand the cookie mechanism:
Let's take a look at the creation and acquisition of cookies
The code in cookie.jsp means: If there is no cookie in the request, it will be created and returned. If the request contains a cookie, it will output a cookie key-value pair (name-value)
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8" session="false"%><!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><%Cookie[] cookies = request.getCookies();if(cookies !=null && cookies.length>0){for(Cookie cookie : cookies){out.print(cookie.getName()+":"+cookie.getValue());}}else{out.print("No cookie, is being created and returned");Cookie cookie = new Cookie("name","wyf");response.addCookie(cookie);}%></body></html>First visit
Second visit
The above operation is that we need to close the browser again. Why are we debugging?
Because by default, a cookie is a session-level cookie, stored in the browser's kernel, and the user is deleted after exiting the browser. If you want the browser to store the cookie on disk, you need to use maxAge, which is in seconds
Let's take a look at persistent cookies
<%Cookie[] cookies = request.getCookies();if(cookies !=null && cookies.length>0){for(Cookie cookie : cookies){out.print(cookie.getName()+":"+cookie.getValue());}}else{out.print("No cookie, is being created and returned");Cookie cookie = new Cookie("name","wyf");cookie.setMaxAge(30);response.addCookie(cookie);}%>cookie.setMaxAge(30); set to 30 seconds, so I won't take a screenshot here. Just say it's under your name. If you don't have cookies for the first time, you can create cookies for the second time. If you don't have cookies for the second time, you can close the browser and access within 30 seconds. You still prompt the cookies for the key-value pair, instead of the previous prompt, you don't have cookies for the cookies for the previous one. You don't have cookies for the cookies for the previous one.
Automatic login
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><form action="success.jsp" method="post">name:<input type="text" name="name"/><input type="submit" value="sumit"//</form></body></html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8" session="false"%><!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><%//If you can get the parameter name, print the login information, store the information in the cookie, and set the time of cookie String name = request.getParameter("name");if (name != null && !name.trim().equals("")) {Cookie cookie = new Cookie("nameCookie", name);cookie.setMaxAge(60);response.addCookie(cookie);} else {//If there is no parameter, you can log in with a cookie and read user information from the cookie. If there is, print the welcome message Cookie[] cookies = request.getCookies();if (cookies != null && cookies.length > 0) {for (Cookie cookie : cookies) {String cookieName = cookie.getName();if ("nameCookie".equals(cookieName)) {String val = cookie.getValue();name = val;}}}}if (name != null && !name.trim().equals("")) {out.print("hello" + name);} else {//If there are no request parameters and no cookies, redirect to login.jspresponse.sendRedirect("login.jsp");}%></body></html> The first time you visit http://localhost:8080/day01/login.jsp, enter the name parameter value and submit it. In success.jsp, first get the submitted parameter name value. If it is not null, then set a cookie directly, save the parameter name value, and then output the name parameter value on the page. When you visit the second time, you directly enter http://localhost:8080/day01/success.jsp,
Since this time we carry the parameter name value, we only need to get the value from the value value of the cookie and then display the output
Show recent shopping history
books.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><h4>Books Page</h4><a href="book.jsp?book=JavaWeb">JavaWeb</a><a href="book.jsp?book=Java">Java</a><a href="book.jsp?book=Oracle">Oracle</a><a href="book.jsp?book=Ajax">Ajax</a><a href="book.jsp?book=JavaScript">JavaScript</a><a href="book.jsp?book=Android">Android</a><a href="book.jsp?book=Jbpm">Jbpm</a><br><br><%//Get all cookiesCookies[] cookies = request.getCookies();//Cookies from the filtered Book, if cookieName is ATGUIGU_BOOK_, it meets the conditions if(cookies!=null&&cookies.length>0){for(Cookie c:cookies){String cookieName = c.getName();if(cookieName.startsWith("Safly")){//Show cookieValueout.println(c.getValue());out.print("<br>");}}}%></body></html>book.jsp
<%@page import="java.util.ArrayList"%><%@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>Book:<%= request.getParameter("book") %><br><br><a href="books.jsp">return</a><%String book = request.getParameter("book");//Determine the cookie to be deleted Cookie[] cookies = request.getCookies();//Save all cookies starting with SaflyArrayList<Cookie> bookCookies = new ArrayList<Cookie>();//Usely use it to save and books.jsp The cookie matched by the incoming book Cookie tempCookie = null;if(cookies!=null&&cookies.length>0){for(Cookie c:cookies){String cookieName = c.getName();if(cookieName.startsWith("Safly")){bookCookies.add(c);//After selecting 5, selecting one of the 5 if(c.getValue().equals(book)){out.print("c.getValue().equals(book)");tempCookie = c;}}}}}//Select 5 books other than these 5 books if(bookCookies.size() >= 5&&tempCookie == null){tempCookie = bookCookies.get(0); //out.print("tempCookie == null");}//If it is in it, delete the bookCookie itself, delete the duplicate cookies in the list, and pass it back if(tempCookie != null){tempCookie.setMaxAge(0); response.addCookie(tempCookie);}//Return the book passed from books.jsp as a cookie cookie cook = new Cookie("Safly"+book,book);response.addCookie(cook);%></body></html>Let’s talk about the logical relationship:
In Books.jsp, below is a list of books.
JavaWeb
Java
Oracle
Ajax
JavaScript
Android
Jbpm
I randomly select a link (such as JavaWeb) to jump to book.jsp. The first time I accessed it, there was no cookie, so I called the following method of book.jsp and created a cookie. In the book.jsp page, click return to return to books.jsp and take out the cookieValue brought by cooks.jsp, and then display the selected book list.
Cookie cook = new Cookie("Safly"+book,book);response.addCookie(cook); Now we have returned to books.jsp and have selected a book JavaWeb. We are choosing a book (assuming Java), and then jumping to books.jsp. At this moment, we will bring a cookie (it was passed to me when JavaWeb was selected for the first time to access books.jsp). The key value of this cookie is SaflyJavaWebJavaWeb, but what? Selecting the second book Java does not come with cookies (no SaflyJava)
Then enter cooks.jsp
if(cookieName.startsWith("Safly")){bookCookies.add(c);}So, put SaflyJavaWebJavaWeb into a bookcookies (storing the selected book list) and then, the SaflyJavaJava will be created. When you click on Renturn, give cookies.jsp reverse
. . . . When choosing a book for 3rd, 4th, and 5th times, it is the same process. If you choose 5 books in books.jsp, how to deal with it when choosing one of these 5 books?
c.getValue().equals(book) to get the selected book. We need to delete this cookie and then add it again and pass it back to the cookies.jsp code as follows:
tempCookie.setMaxAge(0);response.addCookie(tempCookie);
If you choose 5 books in books.jsp and choose the 6th book that is not the 5 books, how to deal with it?
Let's just tempCookie = bookCookies.get(0); take out the first book of the 5 books, then tempCookie.setMaxAge(0); delete the first cookie, then create the cookie back to cookies.jsp
Here are some screenshots:
The action path of cookies
cookie2.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><%String cookieValue = null;Cookie [] cookies = request.getCookies();if(cookies!=null&& cookies.length>0){for(Cookie cookie:cookies){if("cookiePath".equals(cookie.getName())){cookieValue = cookie.getValue();}}}if(cookieValue != null){out.print(cookieValue);}else{out.print("No specified cookie");}%></body></html>writerCookie.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><%//can function as the current directory and subdirectories of the current directory, but cannot act on the previous directory of the current directory//can set the scope of the cookie through setPath,/represents the root directory of the site Cookie = new Cookie("cookiePath","CookiePathValue");cookie.setPath(request.getContextPath());response.addCookie(cookie);%><a href="../cookie2.jsp">to cookie2.jsp</a></body></html>to cookie2.jsp is the cookie2.jsp that accesses the writerCookie.jsp upper directory
The above is the JavaWeb development using cookies to create - obtain - persistence, automatic login, shopping records, and function paths. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!