本篇文章主要讲解使用springboot本身的cookies管理能力实现对cookie数据的增删改查的详细代码实例教程。
作者:任聪聪
日期:2024年8月18日
独立博客:https://rccblogs.com/611.html
文章附件:https://download.csdn.net/download/hj960511/89649817 结合文章附件运行体验可以更为快速的掌握此项能力。
一、实际效果
二、代码实例
步骤一、通过阿里巴巴的构建项目工具构建一个演示项目如下图:
步骤二、清理目录,并构建新的目录如下:
步骤三、构建工具类:
package com.cookiesDemo.utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.WebRequest;
import org.springframework.stereotype.Component;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
@Component
public class CcCookiesUtils {
private HttpServletRequest getRequest() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return attributes.getRequest();
}
private HttpServletResponse getResponse() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return attributes.getResponse();
}
/**
* 设置 cookie
* @param name
* @param value
* @param maxAge 过期时间 单位毫秒
*/
public void setCookieWithExpiry(String name, String value, int maxAge) {
HttpServletResponse response = getResponse();
Cookie cookie = new Cookie(name, value);
cookie.setMaxAge(maxAge); // 设置 cookie 的生存时间
cookie.setPath("/"); // 设置 cookie 的路径
response.addCookie(cookie); // 添加到 response 中
}
/**
* 获取 cookie
* @param name
* @return
*/
public Cookie getCookie(String name) {
HttpServletRequest request = getRequest();
Cookie[] cookies = request.getCookies();
if (cookies != null) {
return Arrays.stream(cookies)
.filter(cookie -> cookie.getName().equals(name))
.findFirst()
.orElse(null);
}
return null;
}
/**
* 判断 cookie 是否存在
* @param name
* @return
*/
public boolean isCookieExist(String name) {
return getCookie(name) != null;
}
/**
* 清除 cookie
* @param name
*/
public void clearCookie(String name) {
setCookieWithExpiry(name, "", -1); // 设置生存时间为负数,浏览器会立即删除该 cookie
}
}
步骤四、构建控制器方法:
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cookiesDemo.web;
import com.cookiesDemo.utils.CcCookiesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author <a href="mailto:[email protected]">theonefx</a>
*/
@Controller
public class BasicController {
@Autowired
private CcCookiesUtils ccCookiesUtils;
//设置cookie
@RequestMapping("/set")
@ResponseBody
public String setCookie(@RequestParam("name") String name, @RequestParam("value") String value, @RequestParam("maxAge") int maxAge) {
ccCookiesUtils.setCookieWithExpiry(name, value, maxAge);
return "设置:"+name+" 内容:"+value+" 成功~";
}
//读取cookie
@RequestMapping("/get")
@ResponseBody
public String getCookie(@RequestParam("name") String name) {
return ccCookiesUtils.isCookieExist(name)?ccCookiesUtils.getCookie(name).getValue():"不存在此cookie:"+name;
}
//判断是否存在
@RequestMapping("/exist")
@ResponseBody
public String isCookieExist(@RequestParam("name") String name) {
return ccCookiesUtils.isCookieExist(name)?"存在此cookie:"+name:"不存在此cookie:"+name;
}
@RequestMapping("/clear")
@ResponseBody
public String clearCookie(@RequestParam("name") String name) {
ccCookiesUtils.clearCookie(name);
return "清除:"+name+" 成功~";
}
}
步骤五、构建演示页面的内容:
<html>
<head>
<title>Cookies 操作代码实例 </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p>Cookies 操作代码实例</p>
<a href="/set?name=lucky&value=任聪聪&maxAge=666666">/set?key=lucky&value=任聪聪&maxAge=666666</a>
<br>
<a href="/get?name=lucky">/get?key=lucky</a>
<br>
<a href="/exist?name=lucky">/exist?key=lucky 判断是否存在</a>
<br>
<a href="/clear?name=lucky">/clear?name=?name=lucky 清空指定的cookies</a>
</body>
</html>