In Spring Boot, you can add headers to an HTTP response by using HttpServletResponse or ResponseEntity inside a web controller
For adding headers to all HTTP responses, use HttpServletResponse inside a Filter implementation along with using @WebFilter and @Component annotations
Add headers to a specific response inside a web controller
Declare an HttpServletResponse parameter in your controller request mapping and use setHeader(name, value)
method
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletResponse;
@Controller
public class WebController {
@GetMapping("/viewController")
public String viewController(HttpServletResponse response){
response.setHeader("header name", "header value");
return "viewName";
}
}
You can also auto-wire HttpServletResponse as a variable
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletResponse;
@Controller
public class WebController {
@Autowired
HttpServletResponse response;
@GetMapping("/viewController")
public String viewController(){
response.setHeader("header name", "header value");
return "viewName";
}
}
If your controller is a REST API endpoint, use ResponseEntity
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
@RestController
public class WebController {
@GetMapping("/restController")
public ResponseEntity restController(){
return ResponseEntity.ok()
.header("header name", "header value")
.body("");
}
}
Add headers to all responses with Filter
Create a new class to implement javax.servlet.Filter
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
@Component
public class ApplicationFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
httpServletResponse.setHeader("header name", "header value");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
The @WebFilter annotation defines which URI patterns you would like to apply the filter on, the /*
value represents for all URI endpoints
The @Component annotation is required to allow Spring Boot to recognize your implementation
Conclusion
In this article, we learned about adding headers to a specific and all HTTP responses in Spring Boot applications