struts2中的通配符

来源:互联网 发布:bash shell windows 编辑:程序博客网 时间:2024/05/20 18:40

在上一篇《struts2中的动态方法调用DMI》中,介绍了通过DMI方式进行不同action的跳转控制。另外,可以通过使用通配符更加灵活的进行配置信息的精简。举例如下:

  场景:进行用户的增、删、改。

(1)UserAction

package com.struts2.study.yy;import com.opensymphony.xwork2.ActionSupport;public class UserAction extends ActionSupport {private static final long serialVersionUID = 1L;public String add(){return SUCCESS;}public String delete(){return SUCCESS;}public String modify(){return SUCCESS;}}
(2)struts.xml

<package name="user" extends="struts-default" namespace="/user">    <action name="User*" class="com.struts2.study.yy.UserAction" method="{1}">    <result>/user/user_{1}_success.jsp</result>    </action>    </package>
此处使用通配符,其中*匹配所有,在method中的{1}表示匹配第一个*,其中跳转页面的命名也是根据第一个*的值进行的。

(3)入口main.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'main.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>   <a href="<%=path%>/user/Useradd">add user</a><br>   <a href="<%=path%>/user/Userdelete">delete user</a><br>   <a href="<%=path%>/user/Usermodify">modify user</a>  </body></html>
(4)user_add_success.jsp、 user_delete_success.jsp、user_modify_success.jsp省略

(5)结果

当访问main.jsp中的链接时,会自动导向跳转的页面。

更进一步,对于不同的Action,可以更加精简的进行配置,如下所示:

 <action name="*_*" class="com.struts2.study.yy.{1}Action" method="{2}">            <result>/{1}_{2}_success.jsp</result>  </action>
其中action中的name值:表示action名字;

class中的{1}匹配name中的第一个*;
method中的{2}匹配name中的第二个*;

result中页面的命名分别取name中的第一个*和第二个*。

举例:比如name="User_add" ,则class=""com.struts2.study.yy.UserAction"  method="add" 页面为User_add_success.jsp

           比如name="Emp_delete,则class="com.struts2.study.yy.EmpAction" method="delete"  页面为Emp_delete_success.jsp


      需谨记:约定大于配置!




0 0