Servlet 3.1 读取 Cookie

Java Servlet 可以使用 HttpServletRequest 类的 getCookies( ) 获取 Cookies

getCookies( ) 方法会返回一个 javax.servlet.http.Cookie 对象的数组

然后遍历数组,使用使用 getName() 和 getValue() 方法就能得到每个 cookie 和关联的值

范例

下面的范例可以读取上一章节中设置的 Cookie

// author: 简单教程(www.twle.cn)
// Copyright © 2015-2065 www.twle.cn. All rights reserved.

package cn.twle.demo;


import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.URLDecoder;
import javax.servlet.annotation.WebServlet;;

@WebServlet(name = "ReadCookiesServlet", urlPatterns = {"read_cookie"}, loadOnStartup = 1) 

public class ReadCookiesServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    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 范例| 简单教程(www.twle.cn)";
        String docType = "<!DOCTYPE html>\n";
        out.println(docType +
                   "<title>" + title + "</title>" +
                   "<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(
              "<p style=\"color:red\">No Cookie founds</h2>");
        }
    }
}

在浏览器上输入 http://localhost:8080/servlet/read_cookie 显示结果如下

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2018 简单教程 twle.cn All Rights Reserved.