Struts2的工作原理3

来源:互联网 发布:mac os 10.13发布时间 编辑:程序博客网 时间:2024/05/22 05:24
3.3 Struts2源代码分析

      和Struts1.x不同,Struts2的启动是通过FilterDispatcher过滤器实现的。下面是该过滤器在web.xml文件中的配置:

代码清单6:web.xml(截取)

   <filter>

      <filter-name>struts2</filter-name>

      <filter-class>

           org.apache.struts2.dispatcher.FilterDispatcher

      </filter-class>

   </filter>

   <filter-mapping>

      <filter-name>struts2</filter-name>

      <url-pattern>/*</url-pattern>

   </filter-mapping>

Struts2建议,在对Struts2的配置尚不熟悉的情况下,将url-pattern配置为/*,这样该过滤器将截拦所有请求。

实际上,FilterDispatcher除了实现Filter接口以外,还实现了StrutsStatics接口,继承代码如下:

代码清单7:FilterDispatcher结构

public class FilterDispatcher implements StrutsStatics, Filter {

}

StrutsStatics并没有定义业务方法,只定义了若干个常量。Struts2对常用的接口进行了重新封装,比如HttpServletRequest、HttpServletResponse、HttpServletContext等。 以下是StrutsStatics的定义:


代码清单8:StrutsStatics.java

public interface StrutsStatics {

   /**

    *ConstantfortheHTTPrequestobject.

    */

   public static finalStringHTTP_REQUEST="com.opensymphony.xwork2.dispatcher.HttpServletRequest";

   /**

    *ConstantfortheHTTPresponseobject.

    */

   public static finalStringHTTP_RESPONSE="com.opensymphony.xwork2.dispatcher.HttpServletResponse";

   /**

    *ConstantforanHTTPrequest dispatcher}.

    */

   public static finalStringSERVLET_DISPATCHER="com.opensymphony.xwork2.dispatcher.ServletDispatcher";

   /**

    *Constantfortheservlet context}object.

    */

   public static finalStringSERVLET_CONTEXT="com.opensymphony.xwork2.dispatcher.ServletContext";

   /**

    *ConstantfortheJSPpage context}.

    */

   public static finalStringPAGE_CONTEXT="com.opensymphony.xwork2.dispatcher.PageContext";

   /**ConstantforthePortletContextobject*/

   public static finalStringSTRUTS_PORTLET_CONTEXT="struts.portlet.context";

}

   容器启动后,FilterDispatcher被实例化,调用init(FilterConfig filterConfig)方法。该方法创建Dispatcher类的对象,并且将FilterDispatcher配置的初始化参数传到对象中(详情请参考代码清单10),并负责Action的执行。然后得到参数packages,值得注意的是,还有另外三个固定的包和该参数进行拼接,分别是org.apache.struts2.static、template、和org.apache.struts2.interceptor.debugging,中间用空格隔开,经过解析将包名变成路径后存储到一个名叫pathPrefixes的数组中,这些目录中的文件会被自动搜寻。

原创粉丝点击