前后台cookie交互

cookie是只要你再客户端(浏览器)那的cookie开放并且有数据,每一次请求的时候都会自动添加到HTTP请求报文中。然后后台可以实时接收观察获取这些cookie
js



java

package com.any.demoSpring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

@Controller
public class TestController {
    @RequestMapping(value="postTest.do",method= RequestMethod.POST,produces = "application/text;charset=UTF-8;")
    @ResponseBody
    public String postTest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Cookie[] cookies = request.getCookies();
        System.out.println("Cookie长度:" + cookies.length);           //读取本机共存在多少COOKIE
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals("username")) {
                    System.out.println("cookie:username=" + URLDecoder.decode(cookies[i].getValue(),"UTF-8"));
                }
            }
        } else {
            System.out.println("没有任何Cookie");
        }

        //创建一个cookie
        Cookie cookie = new Cookie("key1", "cookieValue1");
        cookie.setPath("/");// 这个要设置
        // cookie.setDomain(".zhangsan.com");//这样设置,能实现两个网站共用
        cookie.setMaxAge(365 * 24 * 60 * 60);// 不设置的话,则cookies不写入硬盘,而是写在内存,只在当前页面有用,以秒为单位,关闭浏览器就没了
        response.addCookie(cookie);         //添加cookie到响应对象中
        //创建第二个cookie
        cookie = new Cookie("key2", "cookieValue2");
        cookie.setPath("/");
        cookie.setMaxAge(365 * 24 * 60 * 60);
        response.addCookie(cookie);         //添加cookie到响应对象中
        //删除一个cookie:添加第三个Cookie 用这个cookie来毁掉之前的那个cookie 达到删除的效果!
        cookie = new Cookie("username","");//这边得用"",不能用null
        cookie.setPath("/");//设置成跟写入cookies一样的
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "来自后台的数据!";
    }


}

转载至链接:https://my.oschina.net/u/3697...

你可能感兴趣的:(cookie,交互)