struts2中的動態方法呼叫DMI
阿新 • • 發佈:2019-02-04
通常,在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方式,可以簡化配置資訊。