Question

I have a HeaderFilter containing simple String which I want to add to a servlet's html.

When I invoke chain.doFilter(req, resp) in HeaderFilter doFilter() method, the mentioned text is invisible and I thought it could be somehow overwritten? However, when I do not invoke chain.doFilter(req, resp), the text is visible but the rest is not.

What is the problem?


So that's my code in HeaderFilter class:

package com.example;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.util.*;

public class HeaderFilter implements Filter {

private String header = "<table cellpadding='2' cellspacing='2' border='1' width='100%'>"
        + "<tbody><tr><td valign='Top' bgcolor='#000099'>"
        + "<div align='Center'><font color='#ffffff'>Header</font></div></td>"
        + "</tr></tbody></table>";

private Properties encodings = new Properties();

public void init(FilterConfig fc) throws ServletException {
}

public void doFilter(ServletRequest req, ServletResponse resp,
        FilterChain chain) throws IOException, ServletException {

    Locale locale = req.getLocale();
    String charset = (String) encodings.get(locale);
    if (charset == null)
        charset = "windows-1250";
    resp.setContentType("text/html; charset=" + charset);

    PrintWriter out = resp.getWriter();
    out.println(header);

    chain.doFilter(req, resp);
}

public void destroy() {

}
}

Not sure if I should post any other code?

Was it helpful?

Solution

If you read filter essentials, there is written:

Modifying the response headers and data. You do this by providing a customized version of the response.

and

A filter that modifies a response must usually capture the response before it is returned to the client. The way to do this is to pass the servlet that generates the response a stand-in stream. The stand-in stream prevents the servlet from closing the original response stream when it completes and allows the filter to modify the servlet's response.

So the explanation is easy:

When you do not call next item in the filter chain, your code will be written and returned to the browser. But when you pass control to the next filter, it will be replaced.

To achieve your effect, you need to:

  1. call filter chain
  2. grab final response to StringBuilder
  3. find the location of HTML table tag
  4. insert your HTML code
  5. write modified response

See the linked document for code samples.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top