I have a method in which i want to set response header cache-control and pragma :-
public String addUser(@Valid User user, BindingResult bindingResult) { if(bindingResult.hasErrors()) { bindingResult.getFieldError(); return"edit"; } return "redirect:/welcome/profile/"+user.getName(); }
In this method i want to set cache-control and pragma like we do in simple servlet code using HttpservletResponse calling setHeader method :-
response.setHeader("Cache-Control","no-cache,no-store,must-revalidate"); response.setHeader("Pragma","no-cache"); response.setDateHeader("Expires", 0);
I searched spring docs and could not find any direct way to do it, but I found this:-
@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); }
But I dont know how to use it
Setting Response Headers from Servlets The most general way to specify headers is to use the setHeader method of HttpServletResponse. This method takes two strings: the header name and the header value. As with setting status codes, you must specify headers before returning the actual document.
Adding Custom Header for Individual Response We create a very basic HTTP GET endpoint. Within this endpoint, we access the Response object through the HttpContext object. Then, we add a new header, with the name of x-my-custom-header and a value of individual response .
Simple Way to Get HTTP Response Header in Java – conn. getHeaderFields() public Map<String,List<String>> getHeaderFields() Returns an unmodifiable Map of the header fields. The Map keys are Strings that represent the response-header field names.
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"); }
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With