1. 쿠키 란 무엇입니까? 바이두의 네티즌의 의견
간단히 말해서, 쿠키는 서버가 컴퓨터를 사용하여 컴퓨터를 식별하기 위해 사용하여 서버가 컴퓨터에 일시적으로 저장된 정보입니다. 웹 사이트를 탐색 할 때 웹 서버는 먼저 소량의 정보를 보내서 컴퓨터에 넣습니다. 다음에 같은 웹 사이트를 방문하면 웹 서버는 먼저 지난번에 남은 쿠키 정보가 있는지 확인합니다. 그렇다면 쿠키의 내용에 따라 사용자가 판단되고 특정 웹 페이지 컨텐츠를 보내드립니다.
2. 쿠키는 어디에 있습니까?
3. 쿠키를 삭제할 수 있습니까?
4. 쿠키 구현 원리
브라우저의 쿠키 스토어에서 처음으로 브라우저를 요청하면 쿠키가 없습니다.
첫 번째 방문에는 쿠키가 포함되어 있지 않습니다. 브라우저는 쿠키 요청 헤더를 HTTP 요청 메시지에 추가하여 쿠키를 웹 서버로 다시 전달합니다. 브라우저는 쿠키의 정보 조각을 "이름/값"쌍 (이름-값 쌍) 형태로 저장합니다. 다음에 액세스 할 때 웹 서버는 쿠키 정보를 브라우저로 보내기 위해 HTTP 응답 메시지에 세트 쿠키 응답 헤더를 추가합니다.
현실적으로 쿠키를 살펴 보겠습니다
쉽게 관찰 할 수 있도록 쿠키를 만들고 세션 = "false"를 설정하십시오
<%@ page language = "java"contmenttype = "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/tr/html4/loose.dtd"> html> html> http-quiv ="content-type "content ="text/html; charset = utf-8 "> <title> 제목 </title> </head> <new a cookie 쿠키 생성. 쿠키 ( "이름", "wyf"); response.addcookie (쿠키);%> </body> </html>
먼저 cookie.jsp 파일에 액세스하고 IE에 입력합니다.
http : // localhost : 8080/day01/cookie.jsp
요청 헤더에서 첫 번째 방문은 쿠키를 운반하지 않는다는 것을 알 수 있습니다.
응답 헤더에서 Set-Cookie를 통해 다시 전송되어 브라우저의 로컬 쿠키 스토어에 저장됩니다.
변경 사항이 있는지 확인하기 위해 Cook.jsp 파일에 두 번째로 액세스합니다.
요청 헤더에서 액세스는 브라우저의 로컬 쿠키 저장 영역에서 쿠키를 운반하는 요청임을 알 수 있습니다.
다음은 응답 헤더입니다.
대화식 그래프를 사용하여 쿠키 메커니즘을 이해해 봅시다.
쿠키의 창조와 획득을 살펴 보겠습니다.
Cookie.jsp의 코드는 다음을 의미합니다. 요청에 쿠키가 없으면 생성 및 반환됩니다. 요청에 쿠키가 포함되어 있으면 쿠키 키 값 쌍 (이름-값)을 출력합니다.
<%@ page language = "java"contmenttype = "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/tr/html4/loose.dtd"> html> html> http-tequiv ="content-type "content ="text/html; charset = utf-8 "> <title> 제목 </title> </head> <] 쿠키 [] 쿠키 = request.getCookies (); if (쿠키! = null && cookies.length> 0) {for (쿠키 쿠키 : 쿠키) {out.print (cookie.getName ()+":"+cookie.getValue ()); 쿠키 ( "이름", "wyf"); response.addcookie (쿠키);}%> </body> </html>첫 방문
두 번째 방문
위의 작업은 브라우저를 다시 닫아야한다는 것입니다. 왜 우리는 디버깅 하는가?
기본적으로 쿠키는 브라우저의 커널에 저장된 세션 수준 쿠키이며 브라우저를 종료 한 후 사용자가 삭제됩니다. 브라우저가 쿠키를 디스크에 저장하려면 몇 초 만에 Maxage를 사용해야합니다.
지속적인 쿠키를 살펴 보겠습니다
<%쿠키 [] 쿠키 = request.getCookies (); if (쿠키! = null && 쿠키. 쿠키 ( "이름", "wyf"); 쿠키 .setmaxage (30); response.addcookie (쿠키);}%>
Cookie.SetMaxage (30); 30 초로 설정되므로 여기서 스크린 샷을 찍지 않습니다. 당신의 이름 아래 있다고 말하십시오. 쿠키가 처음없는 경우 두 번째로 쿠키를 만들 수 있습니다. 두 번째로 쿠키가없는 경우 브라우저를 닫고 30 초 안에 액세스 할 수 있습니다. 이전 프롬프트 대신 키 값 쌍의 쿠키를 프롬프트합니다. 이전 프롬프트 대신 쿠키를위한 쿠키가 없습니다. 쿠키는 이전 쿠키를위한 쿠키가 없습니다.
자동 로그인
login.jsp
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 Transitional // en" "http://www.w3.org/tr/tr/tr/html4/loose.dtd"> html> html http-tequiv ="content-type "content ="text/html; charset = utf-8 "> <title> ins insit </head> <inspoc action = <insp": type = "text"name = "name"/> <input type = "value ="sumit "// </form> </body> </html>
성공 .JSP
<%@ page language = "java"contmenttype = "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/tr/html4/loose.dtd"> html> html> http-tequiv ="content-type "content ="text/html; charset = utf-8 "> <title> 제목 </title> <body </title> <intinat the parameter name, print the 매개 변수를 얻을 수 있습니다. 쿠키의 정보 및 쿠키 문자열 이름 = requestparameter ( "name"); if (name! = null &&! name.trim (). equals ( ""))) {쿠키 쿠키 = 새 쿠키 ( "namecookie", name); cookie.setmaxage (60); resigns.addcookie (cookie); 쿠키의 쿠키 및 쿠키에서 사용자 정보를 읽으십시오. 환영 메시지 쿠키 [] 쿠키 = request.getCookies (); if (쿠키! = null && cookies.length> 0) {for (쿠키 쿠키 : 쿠키) {string cookiename = cookie.getName (); if ( "nameCookie".Equals (cookiename)) ! = NULL”). name.trim (). equals ( "")) {out.print ( "hello" + name);} else {// 요청 매개 변수가없고 쿠키가 없으면 login.jspresponse.sendredirect ( "login.jsp");}%> </html> http : // localhost : 8080/day01/login.jsp를 처음 방문하면 이름 매개 변수 값을 입력하고 제출하십시오. 성공적으로 JSP에서 먼저 제출 된 매개 변수 이름 값을 가져옵니다. NULL이 아닌 경우 쿠키를 직접 설정하고 매개 변수 이름 값을 저장 한 다음 페이지에서 이름 매개 변수 값을 출력하십시오. 두 번째로 방문하면 http : // localhost : 8080/day01/success.jsp, 직접 입력하십시오.
이 시간 이후로 우리는 매개 변수 이름 값을 전달하기 때문에 쿠키의 값 값에서만 값을 얻은 다음 출력을 표시하면됩니다.
최근 쇼핑 역사를 보여주십시오
BOOKS.JSP
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 Transitional // en" "http://www.w3.org/tr/tr/html4/loose.dtd"> html> html><meta http-tequiv ="content-type "content ="text/html; charset = utf-8 "> <title> 제목 </title> </head> <h4> books </h4> <an 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> <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> <br> <berg // all cookiescookies get. Book, Cookiename이 atguigu_book_ 인 경우 (쿠키! = null && 쿠키.length> 0) {for (cookie c : 쿠키) {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/tr/tr/html4/loose.dtd"> html> html> http-tequiv ="content-type "content ="text/html; charset = utf-8 "> <title> insert title> <book> <book <book"). %> <br> <br> <a href = "books.jsp"> return </a> < %string book = request.getParameter ( "book"); // 쿠키를 삭제할 쿠키 결정 [] 쿠키 = request.getCookies (); // saflyArraylist <cookie> bookicookies = bookcookies = new arraylist를 사용하여 모든 쿠키를 저장합니다. 쿠키는 들어오는 책 쿠키 tempcookie = null; if (cookies! = null && 쿠키.length> 0) {for (cookie c : 쿠키) {string cookiename = c.getname (); if ( "safly") {bookcookies.add (c); if (c.getValue (). equals (book)) {out.print ( "c.getValue (). equals (book)"; tempCookie = c;}}}}} //이 5 권의 책 이외의 5 권의 책을 선택합니다. //out.print("tempcookie == null ");} // 그것이 있다면 BookCookie 자체를 삭제하고 목록에서 중복 쿠키를 삭제하고 if (tempCookie! = null) {tempCookie.setMaxage (0); response.addcookie (tempcookie);} // 책을 쿠키 쿠키로 전달한 책을 반환합니다.논리적 관계에 대해 이야기합시다.
Books.jsp에서 아래는 책 목록입니다.
Javaweb
자바
신탁
Ajax
자바 스크립트
기계적 인조 인간
JBPM
Book.jsp로 점프 할 링크 (예 : Javaweb)를 무작위로 선택합니다. 처음 접근 할 때 쿠키가 없었기 때문에 다음 방법의 Book.jsp를 불러 쿠키를 만들었습니다. Book.jsp Page에서 돌아 오려면 복귀를 클릭하여 Books.jsp로 돌아와 Cooks.jsp가 가져온 Cookievalue를 꺼낸 다음 선택한 책 목록을 표시하십시오.
쿠키 쿡 = 새로운 쿠키 ( "Safly"+Book, Book); response.addcookie (Cook);
이제 우리는 books.jsp로 돌아와서 Javaweb을 선택했습니다. 우리는 책을 선택하고 (Java를 가정하고) books.jsp로 점프합니다. 이 순간, 우리는 쿠키를 가져올 것입니다 (Javaweb가 처음으로 책을 선택하여 Books.jsp에 합의). 이 쿠키의 핵심 가치는 Saflyjavawebjavaweb이지만 무엇입니까? 두 번째 책 선택 Java는 쿠키가 제공되지 않습니다 (Saflyjava 없음)
그런 다음 cooks.jsp를 입력하십시오
if (cookiename.startswith ( "Safly")) {bookcookies.add (c);}따라서 Saflyjavawebjavaweb를 BookCookies (선택한 책 목록 저장)에 넣으면 Saflyjavajava가 만들어집니다. Renturn을 클릭하면 Cookies.jsp 리버스를 제공하십시오
. . . . 3, 4, 5 번 책을 선택할 때 동일한 과정입니다. Books.jsp에서 5 권의 책을 선택하면이 5 권의 책 중 하나를 선택할 때 책을 다루는 방법은 무엇입니까?
c.getValue (). Equals (Book)는 선택한 책을 얻습니다. 이 쿠키를 삭제 한 다음 다시 추가하고 쿠키로 다시 전달해야합니다.
tempcookie.setmaxage (0); response.addcookie (tempcookie);
Books.jsp에서 5 권의 책을 선택하고 5 권의 책이 아닌 6 번째 책을 선택하는 경우 어떻게 처리 하는가?
그냥 tempcookie = bookcookies.get (0); 5 권의 책의 첫 번째 책을 꺼낸 다음 tempcookie.setmaxage (0); 첫 번째 쿠키를 삭제 한 다음 쿠키로 다시 쿠키를 만듭니다.
스크린 샷은 다음과 같습니다.
쿠키의 행동 경로
cookie2.jsp
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 Transitional // en" "http://www.w3.org/tr/tr/html4/loose.dtd"> html> html> http-quiv ="content-type "content ="text/html; charset = utf-8 "> </head> <] 쿠키 <] 쿠키 (쿠키 </head> <%string). request.getCookies (); if (쿠키! = null && cookies.length> 0) {for (쿠키 쿠키 : 쿠키) {if ( "cookiepath".equals (cookie.getname ()) {cookievalue.getValue ();}} if (cookievalue! = null) {out.print (cookievalue);} else {out.print ( "지정된 쿠키 없음");}%> </body> </html>WriterCookie.jsp
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 Transitional // en" "http://www.w3.org/tr/tr/html4/loose.dtd"> html> html> http-quiv ="content-type "content ="text/html; charset = utf-8 "> <title> 제목 </head> </head> <%// rancer hiptories and subdirectories here </head> <body and subdirectories here in intf-8"> <title> insert and html; 디렉토리이지만 현재 디렉토리의 이전 디렉토리에서는 SetPath를 통해 쿠키의 범위를 설정할 수 없습니다.//쿠키의 루트 디렉토리 = new Cookie ( "CookiePath", "CookYepathValue"); Cookie.SetPath (request.getContextPath ()); AddDcookie (cookie); cookie2.jsp </a> </body> </html>
Cookie2.jsp는 writerCookie.jsp 상단 디렉토리에 액세스하는 cookie2.jsp입니다.
위의 것은 쿠키를 사용하여 Javaweb 개발입니다. 획득 - 지속성, 자동 로그인, 쇼핑 레코드 및 기능 경로. 모든 사람에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 모든 사람에게 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!