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);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…