Add a header to a specific response in Spring Boot
This post will discuss how to add a header to a specific response in a Spring Boot application.
There are several ways to add a custom header to a specific response in a Spring Boot application.
1. Using HttpServletResponse
To set the response for a specific controller, we can do something like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; @RestController @RequestMapping(value = "/app/") public class Controller { @ModelAttribute public void setResponseHeader(HttpServletResponse response) { response.setHeader("Cache-Control", "no-cache"); } @RequestMapping(value = "test") public String test() { return "SUCCESS"; } } |
The above code will set the response for all endpoints in the controller. To set response for a specific endpoint in the controller, we can add the HttpServletResponse instance at the endpoint as an argument and then call the setHeader() method of the HttpServletResponse object for setting the headers:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; @RestController public class Controller { @RequestMapping(value = "execute", method = RequestMethod.GET) public String execute(HttpServletResponse response) { response.setHeader("Cache-Control", "no-cache"); return "SUCCESS"; } } |
2. Using ResponseEntity
As demonstrated below, we can also add headers to the ResponseEntity builder with the HttpHeaders class.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class Controller { @RequestMapping(value = "execute") public ResponseEntity<String> execute() { HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CACHE_CONTROL, "no-cache"); return ResponseEntity.ok() .headers(headers) .body("SUCCESS"); } } |
That’s all about adding a header to a specific response in Spring Boot.
Read More:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)