I want to add a header to Http Response, based on the Http Status code in Spring MVC

爱⌒轻易说出口 提交于 2019-12-19 11:53:39

问题


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>


来源:https://stackoverflow.com/questions/29251549/i-want-to-add-a-header-to-http-response-based-on-the-http-status-code-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!