Latest web development tutorials

Servlet ประมวลผลคุกกี้

คุกกี้เป็นแฟ้มข้อความที่เก็บไว้ในคอมพิวเตอร์ไคลเอนต์และยังคงรักษาความหลากหลายของข้อมูลการติดตาม Java Servlet อย่างชัดเจนสนับสนุนคุกกี้ HTTP

ส่งคืนบัตรประจำตัวของผู้ใช้ที่เกี่ยวข้องกับสามขั้นตอน

  • สคริปต์เซิร์ฟเวอร์จะส่งคุกกี้เพื่อเบราว์เซอร์ ตัวอย่างเช่นชื่ออายุหรือหมายเลขประจำตัว
  • เบราว์เซอร์จะเก็บข้อมูลเหล่านี้บนเครื่องคอมพิวเตอร์สำหรับใช้ในอนาคต
  • ครั้งต่อไปที่เบราว์เซอร์ส่งคำขอไปยังเว็บเซิร์ฟเวอร์ใด ๆ เบราว์เซอร์จะส่งข้อมูลคุกกี้ไปยังเซิร์ฟเวอร์เซิร์ฟเวอร์จะใช้ข้อมูลนี้เพื่อระบุตัวตนของผู้ใช้

ในบทนี้จะบอกถึงวิธีการตั้งหรือตั้งค่าคุกกี้วิธีการเข้าถึงพวกเขาและวิธีที่จะลบออก

Servlet คุกกี้การประมวลผลความต้องการของจีนเข้ารหัสและถอดรหัสดังต่อไปนี้:

String   str   =   java.net.URLEncoder.encode("中文");            //编码
String   str   =   java.net.URLDecoder.decode("编码后的字符串");   // 解码

วิเคราะห์คุกกี้

คุกกี้มักจะตั้งอยู่ในข้อมูลส่วนหัว HTTP (แม้ว่า JavaScript ยังสามารถตั้งค่าได้โดยตรงในเบราว์เซอร์คุกกี้) การตั้งค่า Servlet คุกกี้จะส่งหัวต่อไปนี้:

HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; 
                 path=/; domain=w3cschool.cc
Connection: close
Content-Type: text/html

ในขณะที่คุณสามารถมองเห็นส่วนหัวของคุกกี้ชุดมีคู่ค่าชื่อวันเวลา GMT เส้นทางและโดเมน ชื่อและความคุ้มค่าจะเข้ารหัส URL หมดอายุฟิลด์เป็นคำแนะนำที่บอกว่าเบราว์เซอร์หลังจากวันและเวลาที่กำหนดจะ "ลืม" คุกกี้

หากเบราว์เซอร์ของคุณมีการกำหนดให้จัดเก็บคุกกี้ก็จะเก็บข้อมูลนี้จนถึงวันที่หมดอายุ หากเบราว์เซอร์ของผู้ใช้เพื่อให้ตรงกับใด ๆ ของโดเมนคุกกี้และเส้นทางของหน้าก็จะ re-ส่งคุกกี้ไปยังเซิร์ฟเวอร์ ข้อมูลส่วนหัวของเบราว์เซอร์อาจปรากฏดังนี้

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz

Servlet สามารถเข้าถึงได้โดยวิธีการร้องขอคุกกี้request.getCookies ()ซึ่งส่งกลับอาร์เรย์ของวัตถุCookie

วิธีคุกกี้ Servlet

ต่อไปนี้เป็นรายการของวิธีการที่เป็นประโยชน์เมื่อใช้งานใน Servlet Cookie สามารถนำมาใช้

序号方法 & 描述
1public void setDomain(String pattern)
该方法设置 cookie 适用的域,例如 w3cschool.cc。
2public String getDomain()
该方法获取 cookie 适用的域,例如 w3cschool.cc。
3public void setMaxAge(int expiry)
该方法设置 cookie 过期的时间(以秒为单位)。如果不这样设置,cookie 只会在当前 session 会话中持续有效。
4public int getMaxAge()
该方法返回 cookie 的最大生存周期(以秒为单位),默认情况下,-1 表示 cookie 将持续下去,直到浏览器关闭。
5public String getName()
该方法返回 cookie 的名称。名称在创建后不能改变。
6public void setValue(String newValue)
该方法设置与 cookie 关联的值。
7public String getValue()
该方法获取与 cookie 关联的值。
8public void setPath(String uri)
该方法设置 cookie 适用的路径。如果您不指定路径,与当前页面相同目录下的(包括子目录下的)所有 URL 都会返回 cookie。
9public String getPath()
该方法获取 cookie 适用的路径。
10public void setSecure(boolean flag)
该方法设置布尔值,表示 cookie 是否应该只在加密的(即 SSL)连接上发送。
11public void setComment(String purpose)
设置cookie的注释。该注释在浏览器向用户呈现 cookie 时非常有用。
12public String getComment()
获取 cookie 的注释,如果 cookie 没有注释则返回 null。

การตั้งค่าคุกกี้ผ่าน Servlet

โดยการตั้งค่า Servlet คุกกี้เกี่ยวข้องกับสามขั้นตอน

(1) การสร้างวัตถุ Cookie: คุณสามารถเรียกตัวสร้างคุกกี้ที่มีชื่อและความคุ้มค่าคุกกี้คุกกี้ชื่อคุกกี้และคุกกี้ค่าสตริง

Cookie cookie = new Cookie("key","value");

โปรดจำไว้ว่าไม่คำนึงถึงชื่อหรือค่าไม่ควรมีช่องว่างใด ๆ หรือตัวอักษรต่อไปนี้:

[ ] ( ) = , " / ? @ : ;

(2) กำหนดอายุการใช้งานสูงสุด: คุณสามารถใช้วิธีการที่จะระบุ setMaxAge คุกกี้สามารถรักษาเวลาที่ถูกต้อง (เป็นวินาที)เราจะกำหนดระยะเวลาสูงสุด 24 ชั่วโมงคุกกี้

cookie.setMaxAge(60*60*24); 

(3) ส่งคุกกี้ส่วนหัวของการตอบสนอง HTTP: คุณสามารถใช้ response.addCookieเพื่อเพิ่มการตอบสนอง HTTP ส่วนหัวคุกกี้ดังต่อไปนี้:

response.addCookie(cookie);

ตัวอย่าง

ลองปรับเปลี่ยนของเรา แบบฟอร์มข้อมูลกรณี การตั้งค่าคุกกี้ของชื่อและนามสกุล

package com.w3big.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloServlet
 */
@WebServlet("/HelloForm")
public class HelloForm extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloForm() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		// 为名字和姓氏创建 Cookie      
		Cookie name = new Cookie("name",
				URLEncoder.encode(request.getParameter("name"), "UTF-8")); // 中文转码
		Cookie url = new Cookie("url",
		              request.getParameter("url"));
		
		// 为两个 Cookie 设置过期日期为 24 小时后
		name.setMaxAge(60*60*24); 
		url.setMaxAge(60*60*24); 
		
		// 在响应头中添加两个 Cookie
		response.addCookie( name );
		response.addCookie( url );
		
		// 设置响应内容类型
		response.setContentType("text/html;charset=UTF-8");
		
		PrintWriter out = response.getWriter();
		String title = "设置 Cookie 实例";
		String docType = "<!DOCTYPE html>\n";
		out.println(docType +
		        "<html>\n" +
		        "<head><title>" + title + "</title></head>\n" +
		        "<body bgcolor=\"#f0f0f0\">\n" +
		        "<h1 align=\"center\">" + title + "</h1>\n" +
		        "<ul>\n" +
		        "  <li><b>站点名:</b>:"
		        + request.getParameter("name") + "\n</li>" +
		        "  <li><b>站点 URL:</b>:"
		        + request.getParameter("url") + "\n</li>" +
		        "</ul>\n" +
		        "</body></html>");
		}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

รวบรวม HelloFormServlet ก่อนหน้านี้และสร้างรายการที่เหมาะสมในไฟล์ web.xml ไปนี้:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet> 
    <!-- 类名 -->  
    <servlet-name>HelloForm</servlet-name>
    <!-- 所在的包 -->
    <servlet-class>com.w3big.test.HelloForm</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloForm</servlet-name>
    <!-- 访问的网址 -->
    <url-pattern>/TomcatTest/HelloForm</url-pattern>
  </servlet-mapping>
</web-app>
ความพยายามครั้งสุดท้ายที่จะเรียก HTML Servlet หน้าต่อไป

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.com)</title>
</head>
<body>
<form action=/TomcatTest/HelloForm method="GET">
站点名 :<input type="text" name="name">
<br />
站点 URL:<input type="text" name="url" /><br>
<input type="submit" value="提交" />
</form>
</body>
</html>

บันทึกแฟ้มไปยังเนื้อหา HTML ข้างต้น /TomcatTest/test.html ใน

ต่อไปเราจะไปที่ http: // localhost: 8080 / TomcatTest / test.html สาธิต Gif ดังนี้

หมายเหตุ: บางส่วนของเส้นทางดังกล่าวข้างต้นต้องใช้เส้นทางจริงมากขึ้นปรับเปลี่ยนโครงการของคุณ

อ่านผ่าน Servlet คุกกี้

หากต้องการอ่านคุกกี้ที่คุณจำเป็นต้องสร้างวัตถุjavax.servlet.http.CookieโดยการเรียกgetCookiesHttpServletRequest ()วิธีอาร์เรย์แล้วห่วงผ่านอาร์เรย์และใช้ getName () และ getValue () วิธีการเข้าถึงค่าของแต่ละคุกกี้และที่เกี่ยวข้อง

ตัวอย่าง

คุกกี้ให้อ่านชุดตัวอย่างข้างต้น

package com.w3big.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ReadCookies
 */
@WebServlet("/ReadCookies")
public class ReadCookies extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReadCookies() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
    	Cookie cookie = null;
    	Cookie[] cookies = null;
    	// 获取与该域相关的 Cookie 的数组
    	cookies = request.getCookies();
         
         // 设置响应内容类型
         response.setContentType("text/html;charset=UTF-8");
    
         PrintWriter out = response.getWriter();
         String title = "Delete Cookie Example";
         String docType = "<!DOCTYPE html>\n";
         out.println(docType +
                   "<html>\n" +
                   "<head><title>" + title + "</title></head>\n" +
                   "<body bgcolor=\"#f0f0f0\">\n" );
          if( cookies != null ){
            out.println("<h2>Cookie 名称和值</h2>");
            for (int i = 0; i < cookies.length; i++){
               cookie = cookies[i];
               if((cookie.getName( )).compareTo("name") == 0 ){
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                    out.print("已删除的 cookie:" + 
                                 cookie.getName( ) + "<br/>");
               }
               out.print("名称:" + cookie.getName( ) + ",");
               out.print("值:" +  URLDecoder.decode(cookie.getValue(), "utf-8") +" <br/>");
            }
         }else{
             out.println(
               "<h2 class=\"tutheader\">No Cookie founds</h2>");
         }
         out.println("</body>");
         out.println("</html>");
		}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

รวบรวม ReadCookiesServlet ก่อนหน้านี้และสร้างรายการที่เหมาะสมในไฟล์ web.xmlพยายามที่จะเรียกhttp: // localhost: 8080 / TomcatTest/ HelloForm, จะแสดงผลลัพธ์ต่อไปนี้:


ลบคุกกี้โดย Servlet

ลบคุกกี้เป็นเรื่องง่ายมาก หากคุณต้องการลบคุกกี้ที่คุณจะต้องทำตามขั้นตอนต่อไปนี้สามนี้:

  • อ่านคุกกี้ที่มีอยู่และเก็บไว้ในวัตถุคุกกี้
  • ใช้setMaxAge () วิธีการกำหนดอายุคุกกี้ของศูนย์การลบคุกกี้ที่มีอยู่
  • เพิ่มคุกกี้ในส่วนหัวของการตอบสนอง

ตัวอย่าง

ตัวอย่างต่อไปนี้จะลบคุกกี้ที่มีอยู่ชื่อ "URL" ครั้งต่อไปที่คุณเรียก ReadCookies Servlet ก็จะกลับ URL เป็นโมฆะ

package com.w3big.test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DeleteCookies
 */
@WebServlet("/DeleteCookies")
public class DeleteCookies extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteCookies() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
    	Cookie cookie = null;
  	  Cookie[] cookies = null;
        // 获取与该域相关的 Cookie 的数组
        cookies = request.getCookies();
        
  	  	// 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");
   
        PrintWriter out = response.getWriter();
        String title = "删除 Cookie 实例";
        String docType = "<!DOCTYPE html>\n";
        out.println(docType +
                  "<html>\n" +
                  "<head><title>" + title + "</title></head>\n" +
                  "<body bgcolor=\"#f0f0f0\">\n" );
         if( cookies != null ){
           out.println("<h2>Cookie 名称和值</h2>");
           for (int i = 0; i < cookies.length; i++){
              cookie = cookies[i];
              if((cookie.getName( )).compareTo("url") == 0 ){
                   cookie.setMaxAge(0);
                   response.addCookie(cookie);
                   out.print("已删除的 cookie:" + 
                                cookie.getName( ) + "<br/>");
              }
              out.print("名称:" + cookie.getName( ) + ",");
              out.print("值:" + cookie.getValue( )+" <br/>");
           }
        }else{
            out.println(
              "<h2 class=\"tutheader\">No Cookie founds</h2>");
        }
        out.println("</body>");
        out.println("</html>");
		}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

รวบรวม DeleteCookiesServlet ก่อนหน้านี้และสร้างรายการที่เหมาะสมในไฟล์ web.xmlตอนนี้ใช้http: // localhost: 8080 / TomcatTest/ DeleteCookies, จะแสดงผลลัพธ์ต่อไปนี้: