Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9254981
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T11:36:29+00:00 2026-06-18T11:36:29+00:00

I’ve been searching the net and stackoverflow for an example of somebody inserting content

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T11:36:31+00:00Added an answer on June 18, 2026 at 11:36 am

    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);
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using JSon response to parse title,date content and thumbnail images and place
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a French site that I want to parse, but am running into
I am using jsonparser to parse data and images obtained from json response. When
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I have a jquery bug and I've been looking for hours now, I can't
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
I am confused How to use looping for Json response Array in another Array.
this is what i have right now Drawing an RSS feed into the php,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.