Mayank Sharma Mayank Sharma - 8 months ago 43
Java Question

automatically add header to every response

I want to add this header "Access-Control-Allow-Origin", "*" to every response made to the client whenever a request has made for rest controllers in my application to allow cross origin resource sharing Currently I 'm manually adding this header to each and every method like this

HttpHeaders headers = new HttpHeaders();
headers.add("Access-Control-Allow-Origin", "*");

Its working but its very frustrating . I found webContentInterceptor in spring docs which allow us to modify headers on each response

<bean id="webContentInterceptor"
<property name="Access-Control-Allow-Origin" value="*"/>

but when i use this it throws error that property not found of name Access-Control-Allow-Origin so is there any other way we can automatically add header to every response

Update ! Spring framework 4.2 greatly simplifies this by adding @CrossOrigin annotation to either a method or a controller itself


I recently got into this issue and found this solution. You can use a filter to add these headers :


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

public class CorsFilter extends OncePerRequestFilter {

    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
            response.addHeader("Access-Control-Allow-Origin", "*");
            if (request.getHeader("Access-Control-Request-Method") != null
                    && "OPTIONS".equals(request.getMethod())) {
                // CORS "pre-flight" request
                        "GET, POST, PUT, DELETE");
                        "X-Requested-With,Origin,Content-Type, Accept");
            filterChain.doFilter(request, response);


Don't forget add the filter to your spring context:

<bean id="corsFilter" class="my.package.CorsFilter" />

and the mapping in the web.xml:



To go a little further you can specify a Spring profile to enable or disable this filter with something like that:

<beans profile="!cors">
    <bean id="corsFilter" class="my.package.FilterChainDoFilter" />

<beans profile="cors">
    <bean id="corsFilter" class="my.package.CorsFilter" />

(providing the FilterChainDoFilter similar to the CorsFilter but which only does filterChain.doFilter(request, response); in the doFilterInternal(..))