Struts 传智Struts2笔记(7)

来源:互联网 发布:淘宝达人怎么 编辑:程序博客网 时间:2024/06/05 08:53

Struts2的处理流程

StrutsPrepareAndExecuteFilter是Struts 2框架的核心控制器,它负责拦截由<url-pattern>/*</url-pattern>指定的所有用户请求,当用户请求到达时,该Filter会过滤用户的请求。默认情况下,如果用户请求的路径不带后缀或者后缀以.action结尾,这时请求将被转入Struts 2框架处理,否则Struts 2框架将略过该请求的处理。当请求转入Struts 2框架处理时会先经过一系列的拦截器,然后再到Action。与Struts1不同,Struts2对用户的每一次请求都会创建一个Action,所以Struts2中的Action是线程安全的。


为应用指定多个struts配置文件


在大部分应用里,随着应用规模的增加,系统中Action的数量也会大量增加,导致struts.xml配置文件变得非常臃肿。为了避免struts.xml文件过于庞大、臃肿,提高struts.xml文件的可读性,我们可以将一个struts.xml配置文件分解成多个配置文件,然后在struts.xml文件中包含其他配置文件。下面的struts.xml通过<include>元素指定多个配置文件:

Xml代码 复制代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE struts PUBLIC   
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"   
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5. <struts>  
  6.     <include file="struts-user.xml"/>  
  7.     <include file="struts-order.xml"/>  
  8. </struts>  



通过这种方式,我们就可以将Struts 2的Action按模块添加在多个配置文件中。

动态方法调用



如果Action中存在多个方法时,我们可以使用!+方法名调用指定方法。如下:

Java代码 复制代码
  1. public class HelloWorldAction{   
  2.     private String message;   
  3.     ....   
  4.     public String execute() throws Exception{   
  5.         this.message = "我的第一个struts2应用";   
  6.         return "success";   
  7.     }   
  8.        
  9.     public String other() throws Exception{   
  10.         this.message = "第二个方法";   
  11.         return "success";   
  12.     }   
  13. }  


假设访问上面action的URL路径为: /struts/test/helloworld.action
要访问action的other() 方法,我们可以这样调用:
/struts/test/helloworld!other.action
如果不想使用动态方法调用,我们可以通过常量struts.enable.DynamicMethodInvocation关闭动态方法调用。

Xml代码 复制代码
  1. <constant name="struts.enable.DynamicMethodInvocation" value="false"/>  



使用通配符定义action


Xml代码 复制代码
  1. <package name="itcast" namespace="/test" extends="struts-default">  
  2.     <action name="helloworld_*" class="cn.itcast.action.HelloWorldAction" method="{1}">  
  3.         <result name="success">/WEB-INF/page/hello.jsp</result>  
  4.     </action>  
  5. </package>  


Java代码 复制代码
  1. public class HelloWorldAction{   
  2.     private String message;   
  3.     ....   
  4.     public String execute() throws Exception{   
  5.         this.message = "我的第一个struts2应用";   
  6.         return "success";   
  7.     }   
  8.        
  9.     public String other() throws Exception{   
  10.         this.message = "第二个方法";   
  11.         return "success";   
  12.     }   
  13. }  



要访问other()方法,可以通过这样的URL访问:/test/helloworld_other.action