传智Struts2札记(7)

传智Struts2笔记(7)
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 version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<include file="struts-user.xml"/>
	<include file="struts-order.xml"/>
</struts>


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

动态方法调用



如果Action中存在多个方法时,我们可以使用!+方法名调用指定方法。如下:
public class HelloWorldAction{
	private String message;
	....
	public String execute() throws Exception{
		this.message = "我的第一个struts2应用";
		return "success";
	}
	
	public String other() throws Exception{
		this.message = "第二个方法";
		return "success";
	}
}

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


使用通配符定义action



<package name="itcast" namespace="/test" extends="struts-default">
	<action name="helloworld_*" class="cn.itcast.action.HelloWorldAction" method="{1}">
		<result name="success">/WEB-INF/page/hello.jsp</result>
	</action>
</package>


public class HelloWorldAction{
	private String message;
	....
	public String execute() throws Exception{
		this.message = "我的第一个struts2应用";
		return "success";
	}
	
	public String other() throws Exception{
		this.message = "第二个方法";
		return "success";
	}
}


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