/** 
 * This program is an example from the book "Internet 
 * programming with Java" by Svetlin Nakov. It is freeware. 
 * For more information: http://www.nakov.com/books/inetjava/ 
 */ 
import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
 
public class AdvertismentFilter implements Filter { 
    public void init(FilterConfig aFilterConfig) 
            throws ServletException { 
    } 
 
    public void doFilter(ServletRequest aRequest, 
            ServletResponse aResponse, FilterChain aFilterChain) 
            throws IOException, ServletException { 
        PrintWriter responseOutput = aResponse.getWriter(); 
        HttpServletResponse httpResponse = 
            (HttpServletResponse) aResponse; 
        MemoryResponseWrapper responseWrapper = 
            new MemoryResponseWrapper(httpResponse); 
        aFilterChain.doFilter(aRequest, responseWrapper); 
        String contentType = responseWrapper.getContentType(); 
        String originalResp = responseWrapper.toString(); 
        if ((contentType != null) && contentType.toLowerCase(). 
                startsWith("text/html")) { 
            String newResponse = addAdvertisment(originalResp); 
            responseOutput.print(newResponse); 
        } else { 
            responseOutput.println(originalResp); 
        } 
        responseOutput.close(); 
    } 
 
    private String addAdvertisment(String aHtmlText) { 
        int endOfBodyIndex = 
            aHtmlText.toLowerCase().indexOf("</body>"); 
        String htmlBefore; 
        String htmlAfter; 
        if (endOfBodyIndex != -1) { 
            htmlBefore = 
                aHtmlText.substring(0, endOfBodyIndex-1); 
            htmlAfter = aHtmlText.substring(endOfBodyIndex); 
        } else { 
            htmlBefore = aHtmlText; 
            htmlAfter = ""; 
        } 
        String result = 
            htmlBefore + 
            "\n\n<br><p align='center'>" + 
            "<a href='http://www.devbg.org'><img border='0' " + 
            "src='http://www.devbg.org/ads/basd-logo.png'>" + 
            "</a></p>\n\n" + 
            htmlAfter; 
        return result; 
    } 
 
    public void destroy() { 
    } 
} 
 
class MemoryResponseWrapper extends HttpServletResponseWrapper { 
    private CharArrayWriter mOutput; 
 
    public MemoryResponseWrapper(HttpServletResponse aResponse){ 
        super(aResponse); 
        mOutput = new CharArrayWriter(); 
    } 
 
    public String toString() { 
        String result = mOutput.toString(); 
        return result; 
    } 
 
    public PrintWriter getWriter() { 
        PrintWriter printWriter = new PrintWriter(mOutput); 
        return printWriter; 
    } 
}
Back to Internet Programming with Java books's web site