您的位置:首页 > 编程语言 > Java开发

Struts2的工作原理3

2013-08-02 16:29 176 查看
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的数组中,这些目录中的文件会被自动搜寻。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: