gpt4 book ai didi

java - 在过滤器中添加标题作为响应?

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:12 27 4
gpt4 key购买 nike

我需要在每个响应中添加 header 。我打算在下面做

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", "*");
}

}

我想在 filterChain.doFilter(request, response) 之后执行此操作,以便一旦 Controller 处理它,我只需在返回之前添加 header 给客户。是否正确?

但是根据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.

我觉得上面的说法不对。我不能在 filterChain.doFilter(request, response) 之后添加 header 吗?如果不是,为什么?

我正在使用 spring mvc。

最佳答案

filterChain.doFilter 被调用之后,对响应做任何事情都为时已晚。此时,整个响应已经发送到客户端。

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

已经有一个响应包装器:您可以扩展的 HttpServletResponseWrapper。例如:

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

您的过滤器:

@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);
}

关于java - 在过滤器中添加标题作为响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32829124/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com