Cookie的三大操作

 服务器创建cookie并通知客户端保存cookie,客户端有了 Cookie 后,每次请求都通过请求头发送给服务器--Cookie: key1=value1;

 Cookie的创建

    protected void createCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = new Cookie("key1", "value1");
        response.addCookie(cookie);
        // response.setHeader("Set-Cookie","key1=value1"); 直接设置响应头,也可以创建cookie
        response.getWriter().write("Cookie创建成功");
    }

Cookie的查询

    protected void getCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();

        for (Cookie cookie : cookies) {
            response.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>");
        }

        Cookie iWantCookie = CookieUtils.findCookie("key1", cookies);
        if (iWantCookie != null) {
            response.getWriter().write("找到了需要的Cookie");
        }
    }
public class CookieUtils {
    public static Cookie findCookie(String name , Cookie[] cookies){
        if (name == null || cookies == null || cookies.length == 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (name.equals(cookie.getName())) {
                return cookie;
            }
        }
        return null;
    }
}

Cookie的修改

    protected void updateCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 先找到你要删除的Cookie对象
        Cookie cookie = CookieUtils.findCookie("key1", request.getCookies());
        if (cookie != null) {
            cookie.setValue("newValue");// Cookie cookie = new Cookie("key1","newValue1");
            cookie.setPath( req.getContextPath() + "/abc" );
            cookie.setMaxAge(0); // 表示马上删除,都不需要等待浏览器关闭
            cookie.setMaxAge(60 * 60);       
            response.addCookie(cookie);
           response.getWriter().write("Cookie的各种修改");
        }

    }

 涉及到cookie的接口:request.getCookies(); response.addCookie(cookie); response.setHeader("Set-Cookie","key1=value1"); request.isRequestedSessionIdFromCookie();

posted on 2022-03-02 22:00  金满仓  阅读(168)  评论(0)    收藏  举报

导航