很奇葩把,不需要配置servlet,而是配置filter,HttpServletRequest,HttpServletResponse 也看不到了,这就是Struts的特性,隐藏了所有的细节。
Struts2 工作流程
Struts2抛弃了request、response等Servlet API,看上去更像是普通的Java 类。实际上,Struts2的Action都是属于被调用的。在调用Action的方法前,Struts2会从request中获取参数,并通过setter方法设置到action属性中。
Struts2工作流程描述:
-
1、客户端发送一个HttpServletRequest的请求;
-
2、这个请求依次经过过滤器ActionContextCleanUp、其他过滤器(SiteMesh等)最后到FilterDispatcher。FilterDispatcher是控制器的核心,就是MVC的Struts 2实现中控制层(Controller)的核心;
-
3、FilterDispatcher调用ActionMapper确定请求哪个Action,ActionMapper返回一个收集Action详细信息的ActionMaping对象,然后FilterDispatcher把请求的处理权交给ActionProxy;
-
4、ActionProxy调用配置管理器ConfigurationManager从配置文件struts.xml中读取配置信息,找到需要调用的Action类;
-
5、ActionProxy创建ActionInvocation对象,ActionInvocation对象通过代理模式调用Action,但在调用之前,ActionInvocation会根据配置加载Action相关的所有拦截器(Interceptor)。
-
6、 一旦Action执行完毕,ActionInvocation负责根据struts.xml中的配置找到对应的返回结果Result,然后执行这个Result,Result会调用一些模版(JSP)来呈现页面,拦截器(Interceptor)会再次被执行(顺序和Action执行之前相反);
-
7、最后通过HTTPServletResponse返回客户端一个响应。
Struts2 的线程安全
Struts2 的线程是安全的,因为Action不像Struts1一样是单例的,而是每个请求一个实例。
程序入口FilterDispatcher
能拦截所有的URI,进行调度。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>BasicSrtuts2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>struts.action.extension</param-name>
<param-value>action</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>