一般的servlet应用直接使用request\response,使用它们的默认行为,特殊情况下需要改变它们的默认行为,在很多框架级代码中广泛使用。servlet规范提供了HttpServletResponseWrapper HttpServletRequsetWrapper 包装类,定义它们的子类包装原始request或response,扩展它们的默认行为。
问题是如何让servlet容器使用自定义的包装类呢?
可以通过filter在请求开始前封装原始request或response,filter将包装类传递给后面的filter及servlet,jsp,这样它们就都使用到封装的request或response了。
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
chain.doFilter( request, wrapResponse( (HttpServletResponse) response));
}
private static ServletResponse wrapResponse(HttpServletResponse response)
{
return new HttpServletResponseWrapper(response)
{
要重写的方法
。。。}
seam使用该机制实现了重定向的对话支持,即重定向后也能获取对话的对象了。
@Scope(APPLICATION)
@Name("org.jboss.seam.web.redirectFilter")
@Install(precedence = BUILT_IN, classDependencies="javax.faces.context.FacesContext")
@BypassInterceptors
@Filter(within="org.jboss.seam.web.ajax4jsfFilter")
public class RedirectFilter extends AbstractFilter
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
chain.doFilter( request, wrapResponse( (HttpServletResponse) response));
}
private static ServletResponse wrapResponse(HttpServletResponse response)
{
return new HttpServletResponseWrapper(response)
{
@Override
public void sendRedirect(String url) throws IOException
{。。。。。。。。}
}
}
下面是典型使用示例
http://ch-space.iteye.com/blog/479603
http://blog.chenlb.com/2009/07/use-httpservletresponsewrapper-implement-etag-filter.html
http://www.mzone.cc/article/260.html