有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Spring MVC的java Cookie问题

我试图使用@Cookie获取cookie值。但如果cookie值为空,我会得到400个错误。发生了什么? 这是我的控制器:

    public String listContacts(Map<String, Object> map,
            HttpServletResponse response, @CookieValue("flag") String flag) {



        response.addCookie(new Cookie("flag", "In use"));
...

共 (1) 个答案

  1. # 1 楼答案

    尝试在@CookieValue注释中设置required = false

    public String listContacts(Map<String, Object> map,
          HttpServletResponse response, @CookieValue(value = "flag", required = false) String flag) {
    

    默认情况下,spring希望cookie头出现,否则抛出异常:

    Default is true, leading to an exception being thrown in case the header is missing in the request. Switch this to false if you prefer a null in case of the missing header.

    Alternatively, provide a defaultValue, which implicitly sets this flag to false.