寻找使用 servlet 过滤器将内容插入响应的示例 [英] Looking for an example for inserting content into the response using a servlet filter

查看:25
本文介绍了寻找使用 servlet 过滤器将内容插入响应的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在网络和 stackoverflow 上搜索某人使用 servlet 过滤器将内容插入响应的示例,但只能找到人们捕获/压缩输出和/或更改标头的示例.我的目标是在所有 HTML 响应的结束 之前附加一段 HTML.

我正在开发一个解决方案,将 HttpServletResponseWrapper 扩展为使用我自己的 PrintWriter,然后覆盖其上的写入方法.在 write 方法中,我存储最后 7 个字符以查看它是否等于结束正文标记,然后在继续对文档的其余部分进行正常写入操作之前,我编写了 HTML 块加上结束正文标记.

我觉得一定有人已经解决了这个问题,而且可能比我更优雅.我很感激任何有关如何使用 servlet 过滤器将内容插入到响应中的示例.

更新

响应评论,我还尝试从 http 实施 CharResponseWrapper://www.oracle.com/technetwork/java/filters-137243.html.这是我的代码:

PrintWriter out = response.getWriter();CharResponseWrapper 包裹响应 = 新 CharResponseWrapper((HttpServletResponse)响应);chain.doFilter(wrappedRequest,wrappedResponse);字符串 s =wrappedResponse.toString();if (wrappedResponse.getContentType().equals("text/html") &&StringUtils.isNotBlank(s)) {CharArrayWriter caw = new CharArrayWriter();caw.write(s.substring(0, s.indexOf("</body>") - 1));caw.write("WTF</body></html>");response.setContentLength(caw.toString().length());out.write(caw.toString());}别的 {out.write(wrappedResponse.toString());}关闭();

我也在包装请求,但该代码有效并且不应该影响响应.

解决方案

我使用的代码库在处理响应时调用 getOutputStream 方法,而不是 getWriter,因此其他答案中包含的示例无济于事.这是一个更完整的答案,适用于 OutputStream 和 PrintWriter,如果写入器被访问两次,甚至会正确出错.这源自于一个很好的例子,DUMP REQUEST并使用 JAVAX.SERVLET.FILTER 进行响应.

import javax.servlet.*;导入 javax.servlet.http.*;导入 java.io.*;公共类 MyFilter 实现过滤器{private FilterConfig filterConfig = null;私有静态类 ByteArrayServletStream 扩展了 ServletOutputStream{ByteArrayOutputStream 包;ByteArrayServletStream(ByteArrayOutputStream baos){this.baos = baos;}public void write(int param) 抛出 IOException{baos.write(param);}}私有静态类 ByteArrayPrintWriter{私有 ByteArrayOutputStream baos = 新 ByteArrayOutputStream();private PrintWriter pw = new PrintWriter(baos);私有 ServletOutputStream sos = 新 ByteArrayServletStream(baos);公共 PrintWriter getWriter(){返回密码;}公共 ServletOutputStream getStream(){返回sos;}字节[] toByteArray(){返回 baos.toByteArray();}}公共类 CharResponseWrapper 扩展了 HttpServletResponseWrapper{私有 ByteArrayPrintWriter 输出;私有布尔 usingWriter;公共 CharResponseWrapper(HttpServletResponse 响应){超级(响应);usingWriter = false;输出 = 新的 ByteArrayPrintWriter();}公共字节[] getByteArray(){返回 output.toByteArray();}@覆盖公共 ServletOutputStream getOutputStream() 抛出 IOException{//会出错,如果正在使用如果(使用作家){super.getOutputStream();}usingWriter = true;返回 output.getStream();}@覆盖public PrintWriter getWriter() 抛出 IOException{//会出错,如果正在使用如果(使用作家){super.getWriter();}usingWriter = true;返回 output.getWriter();}公共字符串 toString(){返回 output.toString();}}public void init(FilterConfig filterConfig) 抛出 ServletException{this.filterConfig = filterConfig;}公共无效销毁(){filterConfig = null;}public void doFilter(ServletRequest 请求、ServletResponse 响应、FilterChain 链)抛出 IOException, ServletException{CharResponseWrapper 包裹响应 = 新 CharResponseWrapper((HttpServletResponse)响应);chain.doFilter(请求,wrappedResponse);字节[]字节=wrappedResponse.getByteArray();if (wrappedResponse.getContentType().contains("text/html")) {String out = new String(bytes);//在这里做你的替换out = out.replace("", "WTF");response.getOutputStream().write(out.getBytes());}别的 {response.getOutputStream().write(bytes);}}}

I've been searching the net and stackoverflow for an example of somebody inserting content into the response using a servlet filter, but can only find examples of people capturing/compressing the output and/or changing the headers. My goal is to append a chunk of HTML just before the closing </body> of all HTML responses.

I'm working on a solution that extends the HttpServletResponseWrapper to use my own PrintWriter, then overriding the write methods thereon. Inside the write method I'm storing the last 7 characters to see if it's equal to the closing body tag, and then I write my HTML chunk plus the closing body tag, before continuing normal write operations for the rest of the document.

I feel that somebody must have solved this problem already, and probably more elegantly than I will. I'd appreciate any examples of how to use a servlet filter to insert content into a response.

UPDATED

Responding to a comment, I am also trying to implement the CharResponseWrapper from http://www.oracle.com/technetwork/java/filters-137243.html. Here is my code:

PrintWriter out = response.getWriter();
CharResponseWrapper wrappedResponse = new CharResponseWrapper(
        (HttpServletResponse)response);

chain.doFilter(wrappedRequest, wrappedResponse);
String s = wrappedResponse.toString();

if (wrappedResponse.getContentType().equals("text/html") &&
        StringUtils.isNotBlank(s)) {
    CharArrayWriter caw = new CharArrayWriter();
    caw.write(s.substring(0, s.indexOf("</body>") - 1));
    caw.write("WTF</body></html>");
    response.setContentLength(caw.toString().length());
    out.write(caw.toString());
}
else {
    out.write(wrappedResponse.toString());
}

out.close();

I am also wrapping the request, but that code works and shouldn't affect the response.

解决方案

The codebase I am using, calls the getOutputStream method, instead of getWriter when it processes the response, so the examples included in the other answer doesn't help. Here is a more complete answer that works with both the OutputStream and the PrintWriter, even erroring correctly, if the writer is accessed twice. This is derived from the great example, DUMP REQUEST AND RESPONSE USING JAVAX.SERVLET.FILTER.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MyFilter implements Filter
{
    private FilterConfig filterConfig = null;

    private static class ByteArrayServletStream extends ServletOutputStream
    {
        ByteArrayOutputStream baos;

        ByteArrayServletStream(ByteArrayOutputStream baos)
        {
            this.baos = baos;
        }

        public void write(int param) throws IOException
        {
            baos.write(param);
        }
    }

    private static class ByteArrayPrintWriter
    {

        private ByteArrayOutputStream baos = new ByteArrayOutputStream();

        private PrintWriter pw = new PrintWriter(baos);

        private ServletOutputStream sos = new ByteArrayServletStream(baos);

        public PrintWriter getWriter()
        {
            return pw;
        }

        public ServletOutputStream getStream()
        {
            return sos;
        }

        byte[] toByteArray()
        {
            return baos.toByteArray();
        }
    }

    public class CharResponseWrapper extends HttpServletResponseWrapper
    {
        private ByteArrayPrintWriter output;
        private boolean usingWriter;

        public CharResponseWrapper(HttpServletResponse response)
        {
            super(response);
            usingWriter = false;
            output = new ByteArrayPrintWriter();
        }

        public byte[] getByteArray()
        {
            return output.toByteArray();
        }

        @Override
        public ServletOutputStream getOutputStream() throws IOException
        {
            // will error out, if in use
            if (usingWriter) {
                super.getOutputStream();
            }
            usingWriter = true;
            return output.getStream();
        }

        @Override
        public PrintWriter getWriter() throws IOException
        {
            // will error out, if in use
            if (usingWriter) {
                super.getWriter();
            }
            usingWriter = true;
            return output.getWriter();
        }

        public String toString()
        {
            return output.toString();
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException
    {
        this.filterConfig = filterConfig;
    }

    public void destroy()
    {
        filterConfig = null;
    }

    public void doFilter(
            ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {
        CharResponseWrapper wrappedResponse = new CharResponseWrapper(
                (HttpServletResponse)response);

        chain.doFilter(request, wrappedResponse);
        byte[] bytes = wrappedResponse.getByteArray();

        if (wrappedResponse.getContentType().contains("text/html")) {
            String out = new String(bytes);
            // DO YOUR REPLACEMENTS HERE
            out = out.replace("</head>", "WTF</head>");
            response.getOutputStream().write(out.getBytes());
        }
        else {
            response.getOutputStream().write(bytes);
        }
    }
}

这篇关于寻找使用 servlet 过滤器将内容插入响应的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆