cookie是只要你再客户端(浏览器)那的cookie开放并且有数据,每一次请求的时候都会自动添加到HTTP请求报文中。然后后台可以实时接收观察获取这些cookie
1. 您还可以为 cookie 添加一个过期时间(以 UTC 或 GMT 时间)。默认情况下,cookie 在浏览器关闭时删除:
2.
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
@RequestMapping(value="postTest.do",method= RequestMethod.POST,produces = "application/text;charset=UTF-8;")
@ResponseBody
public String postTest(HttpServletRequest request) throws IOException {
Cookie[] cookies = request.getCookies();
System.out.println("cookies[0].getName() = :"+cookies[0].getName());
System.out.println("cookies[0].getValue() = :"+cookies[0].getValue());
return "来自后台的数据!";
}