You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Servlet Response Filter对成功请求不修改响应体,异常场景正常工作

问题:Servlet响应过滤器仅在异常场景生效,成功请求无修改

我实现了一个Servlet响应过滤器,发现它对成功(200 OK)请求的响应体不做任何修改,但在异常场景下却能正常包装并修改响应体。我的代码改编自O'Reilly《Learning Java(第4版)》中的示例。

以下是我根据自身需求修改后的代码:

public class LinkResponseFilter implements Filter {
    FilterConfig filterConfig;
    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        WrappedResponse wrappedResponse = new WrappedResponse((HttpServletResponse) res);
        chain.doFilter(req, wrappedResponse);
        wrappedResponse.close();
    }
    public void destroy() {
    }
    static class WrappedResponse extends HttpServletResponseWrapper {
        boolean linkText;
        PrintWriter client;
        WrappedResponse(HttpServletResponse res) {
            super(res);
        }
        public void setContentType(String mime) {
            super.setContentType(mime);
            if (mime.startsWith("application/fhir+json")) {   //原示例检查的是html类型
                linkText = true;
            }
        }
        public PrintWriter getWriter() throws IOException {
            if (client == null) {
                if (linkText) {
                    client = new LinkWriter(super.getWriter(), new ByteArrayOutputStream());
                } else {
                    client = super.getWriter();
                }
            }
            return client;
        }
        void close() {
            if (client != null) {
                client.close();
            }
        }
    }
    static class LinkWriter extends PrintWriter {
        ByteArrayOutputStream buffer;
        Writer client;
        LinkWriter(Writer client, ByteArrayOutputStream buffer) {
            super(buffer);
            this.buffer = buffer;
            this.client = client;
        }
        public void close() {
            try {
                flush();
                client.write(linkText(buffer.toString()));
                client.close();
            } catch (IOException e) {
                setError();
            }
        }
        String linkText(String text) {
            text = text.replaceAll("resourceType", "None");//原示例逻辑不同
            return text;
        }
    }
}

内容的提问来源于stack exchange,提问作者Ashish Vasikaran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 16:05:02