On Tue, 12 Feb 2002, Keng Wong wrote:
> Date: Tue, 12 Feb 2002 10:12:11 -0800
> From: Keng Wong <[EMAIL PROTECTED]>
> Reply-To: Tomcat Users List <[EMAIL PROTECTED]>
> To: "Tomcat Users List (E-mail)" <[EMAIL PROTECTED]>
> 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) {
super(response);
}
private String saveContentType = null;
public String getContentType() {
return (this.saveContentType);
}
public void setContentType(String contentType) {
super.setContentType(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
>
Craig
--
To unsubscribe: <mailto:[EMAIL PROTECTED]>
For additional commands: <mailto:[EMAIL PROTECTED]>
Troubles with the list: <mailto:[EMAIL PROTECTED]>