元素<forward>则表示了当Action实例的execute()方法运行完毕或,控制器根据Mapping可将响应信息转到适当的地方。如上面现实,如果客户登陆成功,则调用welcome forward,将成功信息返回到/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。