传智播客-struts2(2)-请求路径与filter处理机制

来源:互联网 发布:云计算行业前景 编辑:程序博客网 时间:2024/05/19 23:16

请求路径-action名称搜索顺序
1、获得请求路径的URI,例如url是:http://server/struts2/path1/path2/path3/test.action

 

2、首先寻找namespace为/path1/path2/path3的package,如果不存在这个package则执行步骤3;如果存在这个package,则在这个package中寻找名字为test的action,当在该package下寻找不到action 时就会直接跑到默认namaspace的package里面去寻找action(默认的命名空间为空字符串“”),如果在默认namaspace的package里面还寻找不到该action,页面提示找不到action。

 

3、寻找namespace为/path1/path2的package,如果不存在这个package,则转至步骤4;如果存在这个package,则在这个package中寻找名字为test的action,当在该package中寻找不到action 时就会直接跑到默认namaspace的package里面去找名字为test的action,在默认namaspace的package里面还寻找不到该action,页面提示找不到action。

 

4、寻找namespace为/path1的package,如果不存在这个package则执行步骤5;如果存在这个package,则在这个package中寻找名字为test的action,当在该package中寻找不到action 时就会直接跑到默认namaspace的package里面去找名字为test的action ,在默认namaspace的package里面还寻找不到该action,页面提示找不到action。

 

5、寻找namespace为/的package,如果存在这个package,则在这个package中寻找名字为test的action,当在package中寻找不到action或者不存在这个package时,都会去默认namaspace的package里面寻找action,如果还是找不到,页面提示找不到action。

 

6、如果某package的namespace=“”,则该package被视为默认namespace的package。

 

filter处理机制
web.xml中:
<filter>
 <filter-name>struts2</filter-name>
 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
 <filter-name>struts2</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>

从该文件可以看出struts2框架中,StrutsPrepareAndExecuteFilter是核心控制器。它负责拦截由<url-pattern>/*</url-pattern>指定的所有用户请求,当用户请求到达时,该Filter会过滤用户的请求。当请求转入Struts 2框架处理时会先经过一系列的拦截器,然后再到Action。与Struts1不同,Struts2对用户的每一次请求都会创建一个Action,所以Struts2中的Action是线程安全的。

 

StrutsPrepareAndExecuteFilter是对struts2较早版本的核心控制器FilterDispatcher(文档建议,从struts2.1.3起不再使用该类)的替代,结合了StrutsPrepareFilter与StrutsExecuteFilter的功能。

 

在struts2中,请求--other filters--StrutsPrepareAndExecuteFilter--other filters--响应。可以看出:
1、StrutsPrepareAndExecuteFilter是放在处理“请求”的其他filters之后的;
2、StrutsPrepareAndExecuteFilter处理之后对结果数据和信息不会直接放行。
因为StrutsPrepareAndExecuteFilter直接放行的话,“响应”是在(例如)tomcat容器中直接解析路径所得结果,如果前面的filters定义路径时用到了struts2自己的机制,那么tomcat解析路径时就会出错。

 

如果其他的Filter要访问Struts的特性,这时候不要使用StrutsPrepareAndExecuteFilter ,而是使用StrutsPrepareFilter与StrutsExecuteFilter,并让其他的Filter应位于两者之间。