tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Craig R. McClanahan" <>
Subject Re: Request filters and content type
Date Tue, 12 Feb 2002 19:23:04 GMT

On Tue, 12 Feb 2002, Keng Wong wrote:

> Date: Tue, 12 Feb 2002 10:12:11 -0800
> From: Keng Wong <>
> Reply-To: Tomcat Users List <>
> To: "Tomcat Users List (E-mail)" <>
> Subject: Request filters and content type
> Does anyone know how can I retrieve the content type of a
> response (or to be exact ServletResponse) ? I'm trying to process
> doFilter() based on the ServletResponse and not the
> ServletRequest.
> Eg. if the response's contentType is gif, do something with it.
> I can't use the filter-mapping tag as the response is generated
> on the fly and the request url is too generic.

On the way *in* to the filter, you'll need to create a response wrapper
that overrides the setContentType() method, and includes a
getContentType() method your filter can recognize -- something along the
following lines:

  public class MyResponseWrapper extends HttpServletResponseWrapper {

    public MyResponseWrapper(HttpServletResponse response) {

    private String saveContentType = null;

    public String getContentType() {
      return (this.saveContentType);

    public void setContentType(String contentType) {
      this.saveContentType = contentType;


  public class MyFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response)
     throws IOException, ServletException {

      MyResponseWrapper wresponse =
       new MyResponseWrapper((HttpServletResponse) response);
      ... other stuff as needed ...
      chain.doFilter(request, wresponse); // Pass wrapped response
      String responseContentType = wresponse.getContentType();
      ... other stuff as needed ...



In "Design Patterns" terms, we are decorating the response provided by the
container to add some additional functionality (i.e. saving the content
type so that it can be retrieved later), without impacting the API seen by
the servlet that is ultimately invoked.  This is a very useful general
technique for writing filters.

> Thanks for the help.
> -keng wong


To unsubscribe:   <>
For additional commands: <>
Troubles with the list: <>

View raw message