通常,在struts2中,如果想执行特定的方法,往往会在struts.xml中,配置action的method属性值为要执行的方法名,默认为execute方法。为了程序的扩展,这种方法不推荐,而是使用DMI方式,举例如下(场景为用户的增、删、改):
(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(){
System.out.println("-----add-----");
return SUCCESS;
}
public String delete(){
System.out.println("-----delete-----");
return SUCCESS;
}
public String modify(){
System.out.println("-----modify-----");
return SUCCESS;
}
}
(2)struts.xml
<package name="user" extends="struts-default" namespace="/">
<action name="user" class="com.struts2.study.yy.UserAction">
<result name="success">/user/success.jsp</result>
</action>
</package>
(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 'mainp.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!add">add user</a><br>
<a href="<%=path %>/user!delete">delete user</a><br>
<a href="<%=path %>/user!modify">modify user</a>
</html>
(4)跳转页面success.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 'success.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>
success!
</body>
</html>
(5)结果
当分别点击三个链接时,后台会打出如下日志:
-----add-----
-----delete-----
-----modify-----
通过DMI方式,可以简化配置信息。