Java Web Cookie工具类(后端 javax.servlet.http.Cookie, 前端 jquery.cookie)

Cookie工具类 CookieUtil.java


import com.google.gson.Gson;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.Cookie;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class CookieUtil {
    public static void saveCookie(final Cookie cookie) {
        final ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        attributes.getResponse().addCookie(cookie);
    }

    /**
     * 获取所有 Cookie
     * */
    public static Cookie[] getCookies() {
        final ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getRequest().getCookies();
    }

    /**
     * 打印所有 Cookie
     * */
    public static void printCookies() {
        final Cookie[] c = getCookies();
        final int len = (c == null ? 0 : c.length);
        for (int i = 0; i < len; i++) {
            System.out.println("name: " + c[i].getName() + ", value: " + c[i].getValue());
        }
    }

    /**
     * 添加 Cookie
     * */
    public static void addCookie(final String name, final Object object) {
        try {
            final String v = URLEncoder.encode(new Gson().toJson(object), "UTF-8");
            final Cookie cookie = new Cookie(name, v);
            cookie.setPath("/");
            cookie.setMaxAge(Integer.MAX_VALUE);
            saveCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取 Cookie
     * */
    public static String getCookie(final String name) {
        try {
            final Cookie[] c = getCookies();
            final int len = (c == null ? 0 : c.length);
            for (int i = 0; i < len; i++) {
                if ((name).equalsIgnoreCase(c[i].getName())) {
                    return URLDecoder.decode(c[i].getValue(), "UTF-8");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除 Cookie
     * */
    public static void removeCookie(final String name) {
        try {
            final Cookie[] c = getCookies();
            final int len = (c == null ? 0 : c.length);
            for (int i = 0; i < len; i++) {
                if ((name).equalsIgnoreCase(c[i].getName())) {
                    final Cookie cookie = new Cookie(name, "");
                    cookie.setPath("/");
                    cookie.setMaxAge(0);
                    saveCookie(cookie);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

cookie.html页面


<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8"/>
    <meta name="Generator" content="EditPlus®"/>
    <meta name="Author" content=""/>
    <meta name="Keywords" content=""/>
    <meta name="Description" content=""/>
    <title>Cookie Page</title>
    <!-- Download URL from https://code.jquery.com/ -->
    <script src="/jquery-1.12.4.min.js"></script>
    <!-- Download URL address from https://github.com/carhartl/jquery-cookie -->
    <script src="/jquery.cookie.js"></script>
</head>
<body>
<!-- 插入 Cookie值 -->
<strong id="cookie"></strong>
<script th:inline="javascript" type="text/javascript">
    // 获取 Cookie值
    var cookie = $.cookie('testCookieKey');
    // 插入 Cookie值
    $('#cookie').text(cookie);
    // 输出到 console
    console.log(cookie);
</script>
</body>
</html>

前端使用了 jquery.cookie


    <!-- Download URL address from https://github.com/carhartl/jquery-cookie -->
    <script src="/jquery.cookie.js"></script>

CookieController.java(入口)


import com.test.web.util.CookieUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/cookie")
public class CookieController {
    /**
     * 预设的 Cookie测试键值
     * */
    private static String name = "testCookieKey";

    @RequestMapping("/add")
    public String add() {
        final Long time = System.currentTimeMillis();
        CookieUtil.addCookie(name, time);

        System.out.println("add: " + time);

        return "cookie";
    }

    @RequestMapping("/get")
    public String get() {
        final String time = CookieUtil.getCookie(name);

        System.out.println("get: " + time);

        return "cookie";
    }

    @RequestMapping("/print")
    public String print() {
        CookieUtil.printCookies();
        return "cookie";
    }

    @RequestMapping("/remove")
    public String remove() {
        CookieUtil.removeCookie(name);
        return "cookie";
    }

}

添加 Cookie


http://127.0.0.1:8080/cookie/add

获取指定 Cookie


http://127.0.0.1:8080/cookie/get

删除指定 Cookie


http://127.0.0.1:8080/cookie/remove

如果您觉得有帮助,欢迎点赞哦 ~ 谢谢!!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值