+
95
-

spring boot如何设置浏览器cookie?

spring boot如何设置浏览器COOKIE?

网友回复

+
15
-

1、设置COOKIE

通过 new COOKIE("COOKIE名", "值")来设置,让后通过HttpServletResponse.addCOOKIE发送浏览器添加COOKIE,代码如下:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.COOKIE;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.http.HttpResponse;

@Controller
public class HelloController {
    @RequestMapping("/hello")
    @ResponseBody
    public String Index(HttpServletResponse response) {
        COOKIE COOKIE = new COOKIE("username", "bfw");
        //将COOKIE对象加入response响应
        response.addCOOKIE(COOKIE);
        return "hello";
    }
}

2、读取单个COOKIE

Spring框架提供@COOKIEValue注释来获取HTTP COOKIE的值,此注解可直接用在控制器方法参数中。

@GetMapping("/")
public String readCOOKIE(@COOKIEValue(value = "username",defaultValue = "Atta") String username) {
    return "Hey! My username is " + username;
}

在上述代码段中,请注意defaultValue = "Atta"。如果没...

点击查看剩余70%

我知道答案,我要回答