automatically add header to every response

后端 未结 6 1113
抹茶落季
抹茶落季 2020-11-28 07:43

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 a

6条回答
  •  旧巷少年郎
    2020-11-28 08:15

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

    import java.io.IOException;
    
    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 {
    
        @Override
        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
                    response.addHeader("Access-Control-Allow-Methods",
                            "GET, POST, PUT, DELETE");
                    response.addHeader("Access-Control-Allow-Headers",
                            "X-Requested-With,Origin,Content-Type, Accept");
                }
                filterChain.doFilter(request, response);
        }
    
    }
    

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

    
    

    and the mapping in the web.xml:

    
        corsFilter
        org.springframework.web.filter.DelegatingFilterProxy
    
    
    
        corsFilter
        /*
    
    

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

    
        
    
    
    
        
    
    

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

提交回复
热议问题