One of main advantages of filter in Java is that you can use it to alter or change the response of webpages before the response are sent to the client, without touching any existing code of the web application. For example, you can use filter to add hit counter information at the end of every page; or append company name at the end of webpage titles, etc.

The following picture illustrates the working of filter mechanism uses to modify the response of a webpage:

modify response using java filter

The workflow of the code in the filter should be like this (pseudo code):

class Filter {
     
    public void doFilter(request, response, chain) {
 
        // create a response wrapper to capture the original response
         
        // allow the request to reach the target page, 
        // but the response is written to the wrapper
        
        chain.doFilter(request, wrapper);
         
        // modify the response
        // write the altered content to the response
    }
}

Because the response of a webpage is text/html (character) so we can code a response wrapper class as follows:

package net.codejava;

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

public class CharResponseWrapper extends HttpServletResponseWrapper {
    private CharArrayWriter writer;
     
    public CharResponseWrapper(HttpServletResponse response) {
        super(response);
        writer = new CharArrayWriter();
    }
     
    public PrintWriter getWriter() {
        return new PrintWriter(writer);
    }
     
    public String toString() {
        return writer.toString();
    }
 
}

Note that this response wrapper class must extend the HttpServletResponseWrapper class provided by the Servlet API. It overrides the getWriter() method to return a PrintWriter object that wraps a CharArrayWriter object. So the servlet container will write the response of the target page to this writer – hence the original response is ‘captured’. We also override the toString() method to return the content of the writer as a String.

And the following pseudo code explains how to modify the original response and send the altered response to the client:

// get the writer object of the original response

// get content from the wrapper and modify it

// use the writer object to write altered content to the response

For example, the following filter class snippet modifies the response to put copyright information to the end of very page:

package net.codejava;

import java.io.*;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

@WebFilter("/*")
public class ResponseFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) response);
		
		chain.doFilter(request, wrapper);
		
		PrintWriter responseWriter = response.getWriter();
		
		if (wrapper.getContentType().contains("text/html")) {
			CharArrayWriter charWriter = new CharArrayWriter();
			String originalContent = wrapper.toString();
			
			int indexOfCloseBodyTag = originalContent.indexOf("</body>") - 1;
	         
			charWriter.write(originalContent.substring(0, indexOfCloseBodyTag));
	         
	        String copyrightInfo = "<p>Copyright CodeJava.net</p>";
	        String closeHTMLTags = "</body></html>";
	        
	        charWriter.write(copyrightInfo);
	        charWriter.write(closeHTMLTags);
	         
	        String alteredContent = charWriter.toString();
	        response.setContentLength(alteredContent.length());
	        responseWriter.write(alteredContent);			
		}
		
	}

	@Override
	public void destroy() {
		
	}

}

NOTE: If you use Servlet API 4.0 or newer, you can override only the doFilter() method as Servlet 4.0 implement default methods so you can override only the method you need, not all methods of the interface.

You can use regular expression replace function of the String class to alter the title of every page, for example:

String originalContent = wrapper.toString();

String regex = "<title>(.*?)</title>";
String replacement = "<title>$1 - CodeJava.net</title>";
originalContent = originalContent.replaceAll(regex, replacement);

This appends the text “CodeJava.net” to the end of the title of all pages.

That’s the example of modifying HTTP response using Java filter. Based on the code in this tutorial, you can adjust to meet your need. Thank you for reading.

 

Related Java Filter Tutorials:

Other Java Servlet Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.

Add comment

   


Comments 

#4FilterCansado2023-09-12 07:11
Note that if you do this, you might need to override getOutputStream too, and not only getWriter.
Quote
#3OmK2021-03-16 01:24
String regex = "(.*?)";
String replacement = "$1 - CodeJava.net";
originalContent = originalContent.replaceAll(regex, replacement);


How this reg3x used to append, while is replace all
Quote
#2siva kumar2020-06-10 02:46
How to modify request HTTP method in filter?is it possible change of HTTP method
Quote
#1David2020-04-01 18:12
Where is the wrapper.getContentType method comes from? It isn't defined in the CharResponseWrapper class.
Quote