39

我有一种方法,我想在其中设置响应标头缓存控制和编译指示:-

public String addUser(@Valid User user, BindingResult bindingResult)
{
    if(bindingResult.hasErrors())
    {
        bindingResult.getFieldError();
        return"edit";
    }
    return "redirect:/welcome/profile/"+user.getName();
}

在这种方法中,我想设置缓存控制和编译指示,就像我们在简单的 servlet 代码中使用 HttpservletResponse 调用 setHeader 方法一样:-

response.setHeader("Cache-Control","no-cache,no-store,must-revalidate");
    response.setHeader("Pragma","no-cache");
    response.setDateHeader("Expires", 0);

我搜索了 spring 文档,找不到任何直接的方法,但我发现了这个:-

@RequestMapping("/something")
public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException 
{
    String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader"));
    byte[] requestBody = requestEntity.getBody();
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("MyResponseHeader", "MyValue");
    return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}

但我不知道如何使用它

4

4 回答 4

55

如果要为控制器的每个响应设置标头,可以使用@ModelAttribute注释。

@ModelAttribute
public void setVaryResponseHeader(HttpServletResponse response) {
    response.setHeader("Vary", "Accept");
}    
于 2015-01-23T19:58:53.150 回答
19
  public String addUser(@Valid User user, BindingResult bindingResult,HttpServletRequest request,HttpServletResponse response)
  {
       if(bindingResult.hasErrors())
       {
            bindingResult.getFieldError();
            return"edit";
      }
      response.setHeader("Cache-Control","no-cache,no-store,must-revalidate");
      response.setHeader("Pragma","no-cache");
      response.setDateHeader("Expires", 0);
      return "redirect:/welcome/profile/"+user.getName();
  }
于 2013-08-30T13:52:46.377 回答
6

自 Spring v. 4.1 以来:

@RequestMapping("/something")
public ResponseEntity<MyClass> handle()
{
return ResponseEntity.status(HttpStatus.CREATED)
              .header("header", "value")
              .body(new MyClass());
}
于 2018-06-13T09:24:58.957 回答
0

您可以手动设置标题,如下所示。

进口:

import org.springframework.http.HttpHeaders;

代码:

public ResponseEntity<Map<String, Object>> doSomething() {
   ...
HttpHeaders respHeaders = new HttpHeaders();
respHeaders.add("Pragma", "no-cache");
respHeaders.add("Cache-Control","no-cache,no-store,must-revalidate");
return new ResponseEntity<Map<String, Object>>(respHeaders, HttpStatus.OK);
}
于 2019-09-18T13:20:07.333 回答