且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在过滤器中添加标题响应?

更新时间:2022-10-21 23:22:10

在调用 filterChain.doFilter 后,对响应做任何事情都已经太迟了。在这一点上,整个响应已经发送到客户端。



您需要在您自己的类中构建一个包装响应,将这些包装传递到 doFilter 方法,并处理你的包装中的任何处理。

已经有一个响应包装器: HttpServletResponseWrapper 你可以扩展。例如:
$ b $ pre $ public class MyResponseRequestWrapper extends HttpServletResponseWrapper {
public MyResponseRequestWrapper(HttpServletResponse response){
super响应);


$ / code $ / pre
$ b $您的过滤器:

  @Override 
protected void doFilterInternal(HttpServletRequest请求,
HttpServletResponse响应,FilterChain filterChain)
抛出ServletException,IOException {

HttpServletResponse myResponse =(HttpServletResponse)响应;
MyResponseRequestWrapper responseWrapper = new MyResponseRequestWrapper(myResponse);
responseWrapper.addHeader(Access-Control-Allow-Origin,*);
filterChain.doFilter(request,myResponse);
}


I need to add the header in each response. I am planning to do below

public class MyFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        filterChain.doFilter(request, response);
            response.addHeader("Access-Control-Allow-Origin", "*"); 
    }

}

I would like to do it after filterChain.doFilter(request, response) so that once controller process it, i just add header before returning to client. Is it correct ?

But As per How to write response filter?

After chain.doFilter has returned, it's too late to do anything with the response. At this point, entire response was already sent to the client and your code has no access to it.

Above statement does not look right to me. Can't i add header after filterChain.doFilter(request, response) ? If not why ?

i am using spring mvc.

After filterChain.doFilter is called it's too late to do anything with the response. At this point, the entire response was already sent to the client.

You need to build a wrap response into your own classes, pass these wrappers into doFilter method and handle any processing in your wrappers.

There is already a response wrapper: HttpServletResponseWrapper that you can extend. For example:

public class MyResponseRequestWrapper extends HttpServletResponseWrapper{
    public MyResponseRequestWrapper(HttpServletResponse response) {
        super(response);
    }
}

Your filter:

@Override
protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    HttpServletResponse myResponse = (HttpServletResponse) response;
    MyResponseRequestWrapper responseWrapper = new MyResponseRequestWrapper(myResponse);
    responseWrapper.addHeader("Access-Control-Allow-Origin", "*");
    filterChain.doFilter(request, myResponse);
}