I want to add a header to Http Response, based on

2019-02-20 23:14发布

问题:

I have to add Cache-Control headers to a rest API designed in Spring MVC, based on the Http Response code. If response code is 200, add the header else dont add.

I dont want the client to cache the response, in case it is not 200.

It's not possible in filters/interceptors, as the response is already committed from controller, so can't change response state.

Is there any other way to add header after controller?

回答1:

You can extend org.springframework.web.filter.OncePerRequestFilter to add cache-control header.

public class CacheControlHeaderFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                               HttpServletResponse response, FilterChain filterChain) {
        // Add the header here based on the response code
    }
}

Declare this filter as a spring bean in your configuration.

<bean id="cacheControlHeaderFilter" class="*.*.CacheControlHeaderFilter" />

Plugin the filter in web.xml:

<filter>
    <filter-name>cacheControlHeaderFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>cacheControlHeaderFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>