设置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

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐