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

<body>

<div>
    <input id="inVal" type="text" /><button id="btn">发送</button>
</div>
<script src="../js/lib/jquery-3.2.1.js"></script>
<script>
    $('#btn').click(function () {
        checkCookie();
    });
    function setCookie(cname,cvalue,exdays){
        var d = new Date();
        d.setTime(d.getTime()+(exdays*24*60*60*1000));
        var expires = "expires="+d.toGMTString();
        document.cookie = cname+"="+cvalue+"; "+expires;
    }
    function getCookie(cname){
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) {
            var c = ca[i].trim();
            if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
        }
        return "";
    }
    function checkCookie(){
        var user=getCookie("username");
        if (user!=""){
            alert("欢迎 " + user + " 再次访问");
            $.ajax({
                url: "postTest.do?",
                type: "POST",
                dataType: "text",
                contentType:"application/text;charset=UTF-8",
                data: {"key1":"val1","key2":"val2"},
                success: function(data) {
                    alert(data);
                },
                error: function() {
                    alert("请求出错!");
                }
            });
        }
        else {
            user = prompt("请输入你的名字:","");
            if (user!="" && user!=null){
                setCookie("username",user,30);
            }
        }
    }

</script>
</body>

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...


卿言何故
1 声望0 粉丝

枯燥的生活里要多微笑


引用和评论

0 条评论