Java项目通过SpringBoot实现cookie的增删改查代码实例!

本篇文章主要讲解使用springboot本身的cookies管理能力实现对cookie数据的增删改查的详细代码实例教程。
作者:任聪聪
日期:2024年8月18日
独立博客:https://rccblogs.com/611.html

文章附件:https://download.csdn.net/download/hj960511/89649817 结合文章附件运行体验可以更为快速的掌握此项能力。

一、实际效果

在这里插入图片描述

二、代码实例

步骤一、通过阿里巴巴的构建项目工具构建一个演示项目如下图:

地址:https://start.aliyun.com/
file

步骤二、清理目录,并构建新的目录如下:

file

步骤三、构建工具类:

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:chenxilzx1@gmail.com">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>

步骤六、找到入口文件并使用idea运行:

file

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

任聪聪

创作不易,你的打赏是我的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值