On Fri, 17 Jan 2003, David Orriss Jr wrote:

> Date: Fri, 17 Jan 2003 18:02:32 -0800
> From: David Orriss Jr <[EMAIL PROTECTED]>
> Reply-To: Tomcat Users List <[EMAIL PROTECTED]>
> To: [EMAIL PROTECTED]
> Subject: Filters - get content-type of a response?
>
> Hey there...
>
> The only examples I've found thus far are syntactially incorrect so I'll
> run my question up the flagpole here... <g>
>
> Can I find out the content-type of a *response* in a filter and then act
> on that accordingly?  If so, can someone provide a snippet?  Thanks
> much.
>

There is indeed a way to do this ... the following example hasn't been
tested, but should give you a starting point.

The key problem is that there's no method like getContentType() on the
HttpServletResponse interface, right (at least not until you get to
Servlet 2.4, where it was added)?  OK, no problem ... let's add one.  We
can't change the servlet API, but we *can* create a wrapper around the
response that augments the servlet API, and pass that on to the servlet
that is actually executed.  Something like this:


  public class MyResponseWrapper extends HttpServletResponseWrapper {

    public MyResponseWrapper(HttpServletResponse response) {
      super(response);
    }

    // Store our intercepted content type
    private String contentType = null;

    // Non-servlet API method, but public so our filter can call it
    public String getContentType() {
      return (this.contentType);
    }

    // Intercept the standard setContentType() call and save the value
    public void setContentType(String contentType) {
      super.setContentType(contentType); // Pass the set call on
      this.contentType = contentType;    // Save the value
    }

    // There is more than one way that content type might get set
    public void setHeader(String name, String value) {
      super.setHeader(name, value);      // Pass the set call on
      if ((name != null) &&
          (name.equalsIgnoreCase("Content-Type")) {
        this.contentType = value;        // Save the value
      }
    }

  }


  public class MyFilter implements Filter {

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

        // Create a custom wrapper around the real response
        MyResponseWrapper wresponse =
         new MyResponseWrapper((HttpServletResponse) response);

        // Pass the wrapper on to the next filter or servlet
        chain.doFilter(request, wrappedResponse);

        // We can call our own private API methods on the wrapper
        System.out.println("Content type was " +
                           wrappedResponse.getContentType());

    }

  }


> --
> David Orriss Jr.

Craig McClanahan



--
To unsubscribe, e-mail:   <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>

Reply via email to