首页 > 代码库 > java:Cookie(常用操作)

java:Cookie(常用操作)

 1.常用操作:

package cn.zzsxt.lee.web.cookie;

import java.io.IOException;

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

public class GetCookieServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取cookie信息
        Cookie[] cookies = req.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            System.out.println(cookies[i].getName() + ":" + cookies[i].getValue());
        }

    }

}

 

 

package cn.zzsxt.lee.web.cookie;

import java.io.IOException;

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;

/**
 * @description 
 * 
 * cookie:
 *         在服务器被创建,返回给客户端,并且保存客户端
 *         如果设置了SETMAXAGE(int seconds),会把cookie保存在客户端的硬盘中
 *         如果没有设置,会默认把cookie保存在浏览器的内存中
 *        一旦设置setPath():只能通过设置的路径才能获取到当前的cookie信息
 * @author Seven Lee
 * @date 
 *
 */
@WebServlet("/cookie.sxt")
public class CookieServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 创建cookie对象
        Cookie compCookie = new Cookie("computer", "HP");
        // 服务器把cookie响应给客户端,所有的cookie对象,都会在服务器端创建,通过http响应给客户端(浏览器)

        
        Cookie keyCookie = new Cookie("key", "doubleflybird");
        
        Cookie mouseCookie = new Cookie("mouse", "leishe");
        mouseCookie.setMaxAge(60*60*24*30);//如果不设置使用时间,那么将取不到Cookie的值
        
        System.out.println(req.getContextPath());// 项目名(在tomcat中部署的项目名)
        // /zzsxt/shopping.jsp
        keyCookie.setPath(req.getContextPath()+"/getCookie.sxt");// 一旦设置了cookie的路径,就只能通过这一个路径才能获取到cookie信息
        

        resp.addCookie(compCookie);
        resp.addCookie(mouseCookie);
        resp.addCookie(keyCookie);
    }

}

 

java:Cookie(常用操作)