设置Cookie

@GetMapping("/setCookie")
public String setCookie(HttpServletResponse response) {
    // 创建一个 cookie对象
    Cookie cookie = new Cookie("username", "lixianhe");

    //将cookie对象加入response响应
    response.addCookie(cookie);

    return "Cookie设置成功";
}

获取Cookie

方式一

@GetMapping(value = "/getCookies")
public String readCookies(HttpServletRequest request, HttpServletResponse response) throws IOException {

    //设置contentType,解决中文乱码
    response.setContentType("text/html;charset=utf-8");

    Map<String, Object> map = new HashMap<>();
    
    // 获取Cookie
    Cookie[] cookies = request.getCookies();
    
    // 遍历Cookie
    for (Cookie aCookie : cookies) {
        String name = aCookie.getName();
        String value = aCookie.getValue();
        map.put(name, value);
    }
    return JSON.toJSONString(map);
}

方式二

Spring框架提供@CookieValue注释来获取Cookie的值

@GetMapping("/")
public String readCookie(@CookieValue(value = "username", required = false) String username) {
    return username;
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐