前后台cookie交互

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/3697586/blog/1831318

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值