How to modify HTTP response using Java Filter
- Details
- Written by Nam Ha Minh
- Last Updated on 28 June 2019   |   Print Email
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:
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:
- WebFilter annotation examples
- How to Create Java Servlet Filter
- How to implement authentication filter for Java web application
Other Java Servlet Tutorials:
- Java Servlet for beginners (XML)
- Java Servlet for beginners (Annotation)
- Java Servlet and JSP Hello World Tutorial with Eclipse, Maven and Apache Tomcat
- How to use Session in Java web application
- How to use Cookies in Java web application
- Java File Upload Example with Servlet
- Java File Download Servlet Example
Comments
String replacement = "$1 - CodeJava.net";
originalContent = originalContent.replaceAll(regex, replacement);
How this reg3x used to append, while is replace all