How to set response header in spring mvc
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();
}
Since Spring v. 4.1:
@RequestMapping("/something")
public ResponseEntity<MyClass> handle()
{
return ResponseEntity.status(HttpStatus.CREATED)
.header("header", "value")
.body(new MyClass());
}
If you want to set headers for every response for a controller you can use @ModelAttribute
annotation.
@ModelAttribute
public void setVaryResponseHeader(HttpServletResponse response) {
response.setHeader("Vary", "Accept");
}