ITEEDU

3.4使用ActionForward 导航

元素<forward>则表示了当Action 实例的execute()方法运行完毕或,控制器根据Mapping 可将响应信息转到适当的地方。如上面现实,如果客户登陆成功,则调用welcomeforward,将成功信息返回到/welcome.jsp 页面。在你的execute()方法的结尾可以使用下面的实例代码而返回welcome forward。当然你的welcome forward 必须在action 元素属性中定义,正如上面所声明的那样。

 return  (mapping.findForward("welcome")); 

ActionForward 对象是配置对象。这些配置对象拥有独一无二的标识以允许它们按照有意义的名称如“success”,“failure”等来检索。ActionForward 对象封装了向前进的URL
路径且被请求处理器用于识别目标视图。ActionForward 对象建立自<forward>元素位于struts-config.xml。下面是一个Struts 中<forward>元素例子,属于<action>元素范围。

<action path="/editCustomerProfile"
	type="packageName.EditCustomerProfileAction"
	name="customerProfileForm"  scope="request">
	<forward name="success"  path="/MainMenu.jsp"/>
	<forward name="failure"  path="/CustomerService.jsp"/>
</action>

基于执行请求处理器的execute(… )方法的结果,当传递一个值匹配指定于<forward>元素中name 属性的值的时候,下一个视图可以在execute(… )方法中被开发者用方便的方法org.apache.struts.action.ActionMapping.findForward(…)选择。ActionMapping.findForward(… )方法既从它的本地范围又从全局范围提供一个ActionForward 对象,该对象返回至RequestProcessor 以RequestDispatcher.forward(… )或response.sendRedirect(… )调用下一个视图。当<forward>元素有redirect=“false”属性或redirect 属性不存在的时候,RequestDispatcher.forward(… )被执行;当redirect=“true”是,将调用sendRedirect(… )方法。下例举例说明了redirect 属性的用法:

<forward name="success"  path="/Catalog.jsp" redirect="true"/>

如果redirect=true, URL建立如/contextPath/path 因为HttpServletResponse.sendRedirect(… )中解释URL 采用”/”开头相对于servlet 容器根目录。
如果redirect=false, URI 建立如/path 因为ServletContext.getRequestDisptacher(… )采用虚拟目录相关URL。

<global-forwards>
<forward name="logout"  path="/logout.do"/>
<forward name="error"  path="/error.jsp"/>
</global-forwards>

在此稍稍说一下有关global-forwards 的概念。其在配置文件中描述了整个应用系统可以使用的ActionForward,而不是仅仅是一个特定的Action。