Filter学习2

Servlet2.3 Filter

  1、Servlet Filter概述

  凡是开发过J2EE的web application的人员都知道,经常需要处理以下几种情况:

   访问特定资源(Web 页、JSP 页、servlet)时的身份认证
   应用程序级的访问资源的审核和记录
   应用程序范围内对资源的加密访问,它建立在定制的加密方案基础上
   对被访问资源的及时转换, 包括从 servlet 和 JSP 的动态输出
  
  在servlet2.3之前这些功能处理是很难实现的,但是Java Servlet 2.3 规范新增了不少激动人心的功能,其中之一便是过滤器(Filter),其实这就是我们所说的管道和过滤器体系架构在J2EE中的应用实践. 通过使用该模式使得Web Application开发者能够在请求到达Web资源之前截取请求,在处理请求之后修改应答。其结构图如下:


  一个执行过滤器的Java 类必须实现javax.servlet.Filter 接口。这一接口含有三个方法:

   init(FilterConfig):这是容器所调用的初始化方法。它保证了在第一次 doFilter() 调用前由容器调用。它能获取在 web.xml 文件中指定的filter初始化参数。

   doFilter(ServletRequest, ServletResponse, FilterChain):这是一个完成过滤行为的方法。它同样是上一个过滤器调用的方法。引入的 FilterChain 对象提供了后续过滤器所要调用的信息。

   destroy():容器在销毁过滤器实例前,doFilter()中的所有活动都被该实例终止后,调用该方法。


  2、Filter链介绍

  所有过滤器都服从调用的过滤器链,并通过定义明确的接口得到执行。WebApplication可以指定许多过滤器来完成相关的工作.那么它们就组成一个过滤器链来完成相应的工作.其结构如下图:


  3、例子

  3.1 简单filter

  在PetStore1.3.1中的就存在两个Filter过滤器.其中一个过滤器,完成字符集的编码的转化,如大家经常遇到的汉字编码问题,你只需配置为GBK即可.它从Web.xml之中读取这些参数的配置信息,然后进行编码的转化.另一个是安全校验Fliter,它负责进行安全检查哪些页面可以进行,哪些不可。它们组成一个Filter链,结构图和实现代码如下:


public class EncodingFilter implements Filter {
 private FilterConfig config = null;
 // default to ASCII
 private String targetEncoding = "ASCII";

 public void init(FilterConfig config) throws ServletException {
  this.targetEncoding = config.getInitParameter("encoding");
 }
 //在过滤器中实现字符集编码转化
 public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain)
 throws IOException, ServletException {
 
  HttpServletRequest request = (HttpServletRequest)srequest;
  request.setCharacterEncoding(targetEncoding);
  // move on to the next
  chain.doFilter(srequest,sresponse);
 }
 public void destroy() {
  .................
 }
}

public class SignOnFilter implements Filter {
 public void init(FilterConfig config) throws ServletException {
  this.config = config;
  URL protectedResourcesURL = null;
  try {
   protectedResourcesURL = config.getServletContext().getResource("/WEB-INF/signon-config.xml");
   ...............
  } catch (java.net.MalformedURLException ex) {
   System.out.println("SignonFilter: malformed URL exception: " + ex);
  }
 }

 public void destroy() {
  config = null;
 }
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
 throws IOException, ServletException {
  ........
 }
}

  容器通过 Web 应用程序中的配置描述符 web.xml 文件解析过滤器配置信息。有两个新的标记与过滤器相关:<filter> 和 <filter-mapping>。<filter> 标记是一个过滤器定义,它必定有一个 <filter- name> 和 <filter-class> 子元素。<filter-name> 子元素给出了一个与过滤器实例相关的名字。<filter-class> 指定了由容器载入的实现类。您能随意地包含一个 <init-param> 子元素为过滤器实例提供初始化参数。<filter-mapping> 标记代表了一个过滤器的映射,指定了过滤器会对其产生作用的 URL 的子集。

<!-- Encoding Filter Declaration Start -->
<filter>
 <filter-name>EncodingFilter</filter-name>
 <display-name>Encoding Filter</display-name>
 <description>no description</description>
 <filter-class>com.sun.j2ee.blueprints.encodingfilter.web.EncodingFilter</filter-class>
 <init-param>
  <param-name>encoding</param-name>
  <param-value>UTF-8</param-value>
 </init-param>
</filter>
<!-- Encoding Filter Declaration End -->
<!-- Signon Filter Declaration Start -->
<filter>
 <filter-name>SignOnFilter</filter-name>
 <display-name>SignOn Filter</display-name>
 <description>no description</description>
 <filter-class>com.sun.j2ee.blueprints.signon.web.SignOnFilter</filter-class>
</filter>
<!-- Signon Filter Declaration End -->

<!-- Encoding Filter Mapping Start-->
<filter-mapping>
 <filter-name>EncodingFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Encoding Filter Mapping End -->
<!-- Signon Filter Mapping Start-->
<filter-mapping>
 <filter-name>SignOnFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Signon Filter Mapping End -->

  3.2 复杂的filter

  上面是petstore的例子,演示了通过Fliter修改字符编码和安全认证的功能。下面提供一个示例演示通过修改返回数据(通过过滤器把response的字符串变成大写)。

public class UCaseResponse extends HttpServletResponseWrapper {
 public UCaseResponse(HttpServletResponse response) {
  super(response);
 }

 public PrintWriter getWriter() throws IOException {
  return new UCaseWriter(super.getWriter());
 }
}

public class UCaseWriter extends PrintWriter {
 public UCaseWriter(Writer out) {
  super(out);
 }
 public void write(int c) {
  super.write(Character.toUpperCase( (char) c));
 }
 public void write(char buf[], int off, int len) {
  for (int i = 0;i < len;i++) {
   write(buf[off + i]);
  }
 }
 public void write(String s, int off, int len) {
  for (int i = 0;i < len;i++) {
   write(s.charAt(off + i));
  }
 }
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {
 try {
  filterChain.doFilter(request, new UCaseResponse((HttpServletResponse)(response)));
 }catch(Exception sx) {
  filterConfig.getServletContext().log(sx.getMessage());
}

  该示例使用HttpServletResponseWrapper技术,它是对HttpServletResponse的包装,其实就是装饰(decorate)设计模式的应用.这个例子能够工作的关键是UCaseResponse和UCaseWriter类,它实现了对每个要输出的字符都转成了大写后再写入实际的输出流的功能。

  4、体系架构的实现

  实现一个管道和过滤器一般要注意以下几个方面:

  把系统任务分成一系列处理阶段。

  根据管道和过滤器的设计方案,必须把系统处理的任务分割成相应独立的任务,如日志,数据转化,安全认证等。这样每个阶段仅依赖其前一阶段的输出。通过数据流将所有阶段相连起来。并且你可以进行替换每个步骤,或者可以调整它们之间的顺序,以产生新的结果.如petstore中的编码转化Filter和安全Filter,分成两个独立的处理阶段。

  定义沿每个管道传输的数据格式。

  我们知道每个过滤器,定义一个统一格式以获得最大的灵活性,因为它使过滤器的重组变得容易。如:每个过滤器的方法是doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)它们的参数是必须相同的。

  决定如何实现每个管道连接

  Filter过滤器的连接是推得方式来实现的.前一个过滤器主动的调用filterChain.doFilter(request, response);来实现转向下一个过滤器。

  设计和实现过滤器

  设计每个Filter具有独立的功能,如编码转化,安全校验,等功能.并且每个Fliter都应该在实现javax.servlet.Filter接口。

  建立处理流水线

  过滤器的部署是在Web.xml中进行配置,描述过滤器的实现类以及它们的map关系,来确定它们的顺序。

   其他应用实例

  1、JBOSS

  如果大家对EJB了解,应该知道客户调用EJB实际上并不是直接引用EJB实例(ejb instance).它通过容器来截获客户端的请求,然后按照EJB描述符做些许多相应的工作如,安全校验,事务的处理,线程并发处理等.这样就可以使开发人员仅关心自己的业务逻辑,而不需对复杂的基础服务进行实现.使开发人员从繁琐的工作中解脱出来.集中精力处理自己的业务逻辑,它的结构图如下:


  笔者有幸阅读了JBOSS的源码,分析了Jboss的EJB容器的实现. EJB的容器通过许多拦截器(Inteceptor)来实现,每个拦截器处理一定的功能,一个处理结束后转发给下一个拦截器,最后一个拦截器才把真正调用EJB的实例.其中它的EntityBean 容器的拦截器的结构如下:


  我们看其中的log拦截器

public class LogInterceptor extends AbstractInterceptor{

public Object invoke(Invocation invocation)
throws Exception
{
 boolean trace = log.isTraceEnabled();

 // Log call details
 if (callLogging)
 {
  ......进行log的处理
 }

 //处理结束,把请求转发给下一个拦截器
 return getNext().invoke(invocation);
}

  这些拦截器配置在standardjboss.xml文件中,如下:

<container-interceptors>
 <interceptor>org.jboss.ejb.plugins.LogInterceptor</interceptor>
 <interceptor>org.jboss.ejb.plugins.SecurityInterceptor</interceptor>
 <interceptor>org.jboss.ejb.plugins.TxInterceptorCMT</interceptor>
 <interceptor metricsEnabled="true">org.jboss.ejb.plugins.MetricsInterceptor</interceptor>
 <interceptor>org.jboss.ejb.plugins.EntityLockInterceptor</interceptor>
 <interceptor>org.jboss.ejb.plugins.EntityInstanceInterceptor</interceptor>
 <interceptor>org.jboss.resource.connectionmanager.CachedConnectionInterceptor</interceptor>
 <interceptor>org.jboss.ejb.plugins.EntitySynchronizationInterceptor</interceptor>
 <interceptor>org.jboss.ejb.plugins.cmp.jdbc.JDBCRelationInterceptor</interceptor>
</container-interceptors>

  这就是Jboss容器架构最巧妙的地方,最初这个架构就是由天才少年Rickard Oberg提出的.其实这个架构就应用我们讨论的管道和过滤器模式,其实每个拦截器就是一个过滤器,使用该模式给Jboss带来了如下的好处:

  使系统的架构更容易理解,因为每个过滤器完成单一的功能。

  使系统更加模块化,有利于系统的模块重用和扩展,如果系统想增加某种功能只需增加一个实现Interceptor接口的拦截器,然后配置在standardjboss.xml文件中即可。

  使系统的容易进行错误处理,如果在一个拦截器中发现错误(error)或者异常(exception),只需返回即可.

  2、AXIS

  无独有偶,同样在Axis上也应用了管道和过滤器模式.Aixs是apache开源的webservice实现服务器。简单的说,axis就是处理Message,它首先截获客户端的请求,然后转发到真正的实现业务逻辑上处理客户端的请求,在这之前经过一系列的handler处理.它的结构很像EJB容器.其实就是管道和过滤器模式的应用,Handler就是过滤器.它的处理顺序主要考虑两个方面一个是部署描述符(deployment configuration )另一个就是是客户端还是服务器端。Handler处理的对象是MessageContext它的由3个重要的部分组成,一是一个request Message,一个是response message,还有许多属性。

  我们经研究源码分析,在服务器端,有一个Transport Listener 它监听客户端的请求, 可以通过多种协议,一旦有客户请求,它将按照协议的规范把数据解析生成生成一个Message对象,然后把它设置到MessageContext,然后调用一系列的Handler进行处理。

  其结构图如下:


  相关设计模式

  在使用管道和过滤器模式时,一般会使用以下的GOF设计模式。

  1、职责链模式(Chain Of Responsibility)

  职责链设计模式的意图就是使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。其实管道和过滤器模式就是职责链模式的抽象,把它应用到软件体系架构中。

  2、 命令模式(Command)

  命令模式的意图将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。在管道和过滤器模式中每个过滤器一般使用命令模式,把请求封装成一个命令进行处理。

  3、装饰模式(Decorator)

  装饰模式的意图就是动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。

  在管道和过滤器模式中,在每个过滤器中经常需要对请求进行动态的增加功能,或者修改请求的内容,这时一般会使用装饰模式.如Servlet filter的javax.servlet.http.HttpServletRequestWrapper, javax.servlet.http.HttpServletResponseWrapper就是装饰模式的应用.

  总结

  本文讨论了管道和过滤器模式的解决方案,以及它的优缺点.然后以J2EE规范的Servlet Filter为例详细介绍了怎样应用该模式,同时简单的介绍了在Jboss,Axis中的应用。

struts中文的解决 filter的一种用法

1.使ApplicationResources.properties支持中文
建立一个ApplicationResources_ISO.properties文件,把应用程序用的message都写进去,然后在dos下执行这个命令,
native2ascii -encoding gb2312 ApplicationResources_ISO.properties ApplicationResources.properties
这样就会将ISO编码的ApplicationResources转换成GB2312编码的格式了,同时保存到ApplicationResources.properties.
native2ascii这个工具是jdk自带的一个东东,所以如果path都设定正确就可以直接运行了,你可以在$java_home$/bin下找到他。
转换后的中文类似于这个样子
iso 格式下 :tj.type=商品车类型
gb2312格式下 :tj.type=\u5546\u54c1\u8f66\u7c7b\u578b
然后在struts-config.xml中设置应用这个资源文件
 <message-resources parameter="com.huahang.tj.ApplicationResources" key="org.apache.struts.action.MESSAGE"></message-resources>
开发jsp时在jsp的开头写上,将字符集设置成gb2312就可以了。

2.使数据库操作支持中文。
数据库操作支持中文一直让我比较头痛,但是感谢善解人衣向我推荐了www.chinaxp.org,这个网站是用struts框架开发的,而且
开放源码,下载了源码后发现它的中文处理得很好,阅读部分源码,没有发现什么特殊的字符集转换,很纳闷,偶然看到楼上网友
留言知道原来servlet可以统一设置字符转换。chinaxp.org就是这么做的。
在web.xml中加上

  1. <filter>  
  2.     <filter-name>Set Character Encoding</filter-name>  
  3.     <filter-class>com.huahang.tj.struts.filters.SetCharacterEncodingFilter</filter-class>  
  4.     <init-param>  
  5.       <param-name>encoding</param-name>  
  6.       <param-value>GB2312</param-value>  
  7.     </init-param>  
  8.     <init-param>  
  9.       <param-name>ignore</param-name>  
  10.       <param-value>true</param-value>  
  11.     </init-param>  
  12.   </filter>  
  13.   <filter-mapping>  
  14.     <filter-name>Set Character Encoding</filter-name>  
  15.     <servlet-name>action</servlet-name>  
  16.   </filter-mapping>  

 
这里会涉及一个bean,源码如下:

  1. /*  
  2.  * XP Forum  
  3.  *      
  4.  * Copyright (c) 2002-2003 RedSoft Group.  All rights reserved.  
  5.  *  
  6.  */  
  7. package com.huahang.tj.struts.filters;   
  8.   
  9. import javax.servlet.*;   
  10. import java.io.IOException;   
  11.   
  12. /**  
  13.  * <p>Filter that sets the character encoding to be used in parsing the  
  14.  * incoming request, either unconditionally or only if the client did not  
  15.  * specify a character encoding.  Configuration of this filter is based on  
  16.  * the following initialization parameters:</p>  
  17.  * <ul>  
  18.  * <li><strong>encoding</strong> - The character encoding to be configured  
  19.  *     for this request, either conditionally or unconditionally based on  
  20.  *     the <code>ignore</code> initialization parameter.  This parameter  
  21.  *     is required, so there is no default.</li>  
  22.  * <li><strong>ignore</strong> - If set to "true", any character encoding  
  23.  *     specified by the client is ignored, and the value returned by the  
  24.  *     <code>selectEncoding()</code> method is set.  If set to "false,  
  25.  *     <code>selectEncoding()</code> is called <strong>only</strong> if the  
  26.  *     client has not already specified an encoding.  By default, this  
  27.  *     parameter is set to "true".</li>  
  28.  * </ul>  
  29.  *  
  30.  * <p>Although this filter can be used unchanged, it is also easy to  
  31.  * subclass it and make the <code>selectEncoding()</code> method more  
  32.  * intelligent about what encoding to choose, based on characteristics of  
  33.  * the incoming request (such as the values of the <code>Accept-Language</code>  
  34.  * and <code>User-Agent</code> headers, or a value stashed in the current  
  35.  * user's session.</p>  
  36.  *  
  37.  * @author <a href="mailto:jwtronics@yahoo.com">John Wong</a>  
  38.  *  
  39.  * @version $Id: SetCharacterEncodingFilter.java,v 1.1 2002/04/10 13:59:27 johnwong Exp $  
  40.  */  
  41. public class SetCharacterEncodingFilter implements Filter {   
  42.   
  43.     // ----------------------------------------------------- Instance Variables   
  44.   
  45.   
  46.     /**  
  47.      * The default character encoding to set for requests that pass through  
  48.      * this filter.  
  49.      */  
  50.     protected String encoding = null;   
  51.   
  52.   
  53.     /**  
  54.      * The filter configuration object we are associated with.  If this value  
  55.      * is null, this filter instance is not currently configured.  
  56.      */  
  57.     protected FilterConfig filterConfig = null;   
  58.   
  59.   
  60.     /**  
  61.      * Should a character encoding specified by the client be ignored?  
  62.      */  
  63.     protected boolean ignore = true;   
  64.   
  65.   
  66.     // --------------------------------------------------------- Public Methods   
  67.   
  68.   
  69.     /**  
  70.      * Take this filter out of service.  
  71.      */  
  72.     public void destroy() {   
  73.   
  74.         this.encoding = null;   
  75.         this.filterConfig = null;   
  76.   
  77.     }   
  78.   
  79.   
  80.     /**  
  81.      * Select and set (if specified) the character encoding to be used to  
  82.      * interpret request parameters for this request.  
  83.      *  
  84.      * @param request The servlet request we are processing  
  85.      * @param result The servlet response we are creating  
  86.      * @param chain The filter chain we are processing  
  87.      *  
  88.      * @exception IOException if an input/output error occurs  
  89.      * @exception ServletException if a servlet error occurs  
  90.      */  
  91.     public void doFilter(ServletRequest request, ServletResponse response,   
  92.                          FilterChain chain)   
  93.     throws IOException, ServletException {   
  94.   
  95.         // Conditionally select and set the character encoding to be used   
  96.         if (ignore || (request.getCharacterEncoding() == null)) {   
  97.             String encoding = selectEncoding(request);   
  98.             if (encoding != null)   
  99.                 request.setCharacterEncoding(encoding);   
  100.         }   
  101.   
  102.     // Pass control on to the next filter   
  103.         chain.doFilter(request, response);   
  104.   
  105.     }   
  106.   
  107.   
  108.     /**  
  109.      * Place this filter into service.  
  110.      *  
  111.      * @param filterConfig The filter configuration object  
  112.      */  
  113.     public void init(FilterConfig filterConfig) throws ServletException {   
  114.   
  115.     this.filterConfig = filterConfig;   
  116.         this.encoding = filterConfig.getInitParameter("encoding");  
  117.         String value = filterConfig.getInitParameter("ignore");  
  118.         if (value == null)  
  119.             this.ignore = true;  
  120.         else if (value.equalsIgnoreCase("true"))  
  121.             this.ignore = true;  
  122.         else if (value.equalsIgnoreCase("yes"))   
  123.             this.ignore = true;   
  124.         else  
  125.             this.ignore = false;   
  126.   
  127.     }   
  128.   
  129.   
  130.     // ------------------------------------------------------ Protected Methods   
  131.   
  132.   
  133.     /**  
  134.      * Select an appropriate character encoding to be used, based on the  
  135.      * characteristics of the current request and/or filter initialization  
  136.      * parameters.  If no character encoding should be set, return  
  137.      * <code>null</code>.  
  138.      * <p>  
  139.      * The default implementation unconditionally returns the value configured  
  140.      * by the <strong>encoding</strong> initialization parameter for this  
  141.      * filter.  
  142.      *  
  143.      * @param request The servlet request we are processing  
  144.      */  
  145.     protected String selectEncoding(ServletRequest request) {   
  146.   
  147.         return (this.encoding);   
  148.   
  149.     }   
  150.   
  151. }//EOC   
  152.   

加上这个后,在action中就可以直接从form中接收gb2312编码的数据了,返回时自然也是gb2312了。
但是这个好像需要servlet 2.2以上的容器

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值