jquery cookie 插件使用
********************
常用操作
$.cookie("key","value"):设置cookie
$.cookie("key"):读取cookie
$.cookie("key",null):删除cookie
可选参数:
expires:设置cookie有效期(单位天),设置为负数,cookie会被删除,如果不设置,浏览器关闭时即删除
path:cookie路径属性,默认为创建cookie的页面路径
domain:cookie的域名属性,默认为创建cookie的页面域名
secure:如果设置为true,cookie传输需要安全协议(https)
$.cookie("key","value",{
expires: 7, //有效期7天
path: "/",
domain: "www.baidu.com",
secure: true
})
********************
示例
HelloController
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(HttpServletResponse response){
Cookie cookie=new Cookie("name","瓜田李下");
response.addCookie(cookie);
return "test";
}
}
test.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/jquery/jquery-3.5.1.min.js"></script>
<script src="/jquery/jquery.cookie.js"></script>
</head>
<script>
$(function () {
$("#btn").click(function () {
$("#cookie").val($.cookie("name"))
})
})
</script>
<body>
<div th:align="center">
name: <input type="text" id="cookie" name="cookie" style="background-color: greenyellow"><br>
<button id="btn">获取cookie</button>
</div>
</body>
</html>
使用测试
点击按钮,即可获得cookie值