问题 想从一个模块(源模块)切换到另一个模块(目标模块)。 解决方案 在你的源模块中建立一个type为“org.apache.struts.actions.SwitchAction”的action: <action path="/ChangeModuleTest" type="org.apache.struts.actions.SwitchAction"/> 使用这个action,向它传递两个参数prefix和page。prefix指明了目标模块名称,必须是以斜扛开头(“/”),page指明了相对于目标模块的位置。如: <html:link page="/ChangeModuleTest.do?prefix=moduleName&page=/SomeAction.do"> Change Module </html:link>如果你要连接到一个action,别忘了加上”.do”。 讨论 SwitchAction能将应用程序从一个模块转到另一个模块,然后跳转到目标模块的指定位置。 同ForwardAction、IncludeAction一样SwitchAction不需要子类化。 当我们在浏览器中使用http://hostaddress/contextpath/module/action.do式样的的url时,actionservlet会根据module选择模块对象,下面是actionservlet处理http请求的代码: protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { RequestUtils.selectModule(request, getServletContext()); getRequestProcessor(getModuleConfig(request)).process (request, response); } RequestUtils.selectModule函数将使用下面的代码把url中的模块前缀(下面代码的prefix将代表上面url式样中的/module)指定的模块对象保存在request属性中,这个模块对象就成了处理这个请求的当前模块对象: // Expose the resources for this module ModuleConfig config = (ModuleConfig) context.getAttribute(Globals.MODULE_KEY + prefix); if (config != null) { request.setAttribute(Globals.MODULE_KEY, config); } else { request.removeAttribute(Globals.MODULE_KEY); } 也许你会认为从一个模块跳转到另一个模块可以在一个link或action的URL中使用模块前缀。例如,你已经创建了一个模块admin,你想创建一个从默认模块链接到你的admin模块的主页。你也许会象下面这样写: <html:link action="/admin/Main.do">Admin Module</html:link> 你会发现着段代码不起作用。 要跳转到另一个模块的一个action,请求必须经过控制层,如果你将一个请求直接发送向另一个模块的某个JSP,则struts将不能访问那个模块指定的struts 对象,如资源束,plug-in还有global forwards。SwitchAction可以保证你的请求经过控制层。 既然你不能直接链接到另一个模块的JSP页面,那么你需要在在你的源模块中建立SwitchAction,引用链接路径,传递路径中的prefix和page请求参数。 <html:link page="/SwitchModule.do?prefix=admin&page=/Main.do"> Admin Module </html:link> SwitchAction将通过prefix和page参数指定的信息进行模块跳转。参数信息如下: 参数 描述 举例 Prefix 要跳向的模块名称。这个值必须以”/”开头。如果使用空字符串则表示是默认模块 Prefix=”” Prefix=”/admin” Page 相对于目标模块的JSP或action的URL Page=”/admin.jsp” Page=”/addemployee.do?id=5” 可以使用全局跳转来指定要跳向的URL。当要改变prefix和page的时候你只需要改变全局跳转 <global-forwards> <forward name="goToDefaultModule" contextRelative="true" path="/default_module.jsp"/> <forward name="goToDefaultModuleViaAction" path="/SwitchModule.do?prefix=&page=/default_module.jsp"/> <forward name="goToModule2" path="/SwitchModule.do?prefix=/mod2&page=/module2.jsp"/> </global-forwards> 设置contextRelative=”true”表示你将跳转到默认模块如果你要跳转的目标模块不是默认模块则path必然是一个SwitchAction。创建链接如下: <html:link forward="goToModule2"> Module2 </html:link> forward指定global forwards的名称(name)。 当在path属性中指定参数时,字符”&”不能被直接使用,而是用&代替。这样参数就能被struts正确的处理 在struts1.2中,你可以创建一个链接到另一个模块的某个action而不需要SwitchAction或global forward。module属性指明了模块的前缀名称使用空字符串(“”)表示是默认模块。 <html:link module="/mod2" action="module2Action.do"> Module2 </html:link> 当使用action属性的时候才能使用module属性。如果你想链接到 另一个模块的某个JSP,你的请求必须通过SwitchAction

评论