Struts2中DMI的使用
Struts2的Action类中可以放置多个方法并在struts.xml中配置供页面调用。只要方法符合execute()方法的标准即返回类型是String就可以了。
同一个Action多个方法调用的方式中有三种方法
1.在<action>标签中有一个method的属性可以配置自定义的方法。
2.使用DMI方法。
3.使用通配符
今天我们着重介绍第两种方法的使用:
第一种方法的弊端是你在Action类中定义多少方法就需要使用多少个<action></action>标签,这样会导致struts.xml文件越来越大。
第二种方法的使用:
Action类的:
package test.struts2.DMI;import com.opensymphony.xwork2.ActionSupport;public class TestDMI extends ActionSupport {private String message;public String getMessage() {return message;}public String searchUsers()throws Exception{message = "你调用的是searchUsers()查询方法!";return SUCCESS;}public String addUser()throws Exception{message = "你调用的是addUser()添加方法!";return SUCCESS;}}
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd" ><struts><constant name="struts.i18n.encoding" value="GBK"></constant><package name="struts2" extends="struts-default" namespace="/"> <action name="user" method="addUser"><result>result.jsp</result></action><action name="userSearch" method="searchUsers"><result>result.jsp</result></action></package> </struts>
<%@ page language="java" pageEncoding="GBK"%><%String path = request.getContextPath();%><html> <head> <title>Struts DMI</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"> </head> <body> <a href="userAdd">通过普通调用addUser()方法</a> <br/> <a href="userSearch">通过普通调用searchUsers()方法</a> <hr> <a href="user!addUser">通过DMI方式调用addUser()方法</a> <br/> <a href="user!searchUsers">通过DMI方式调用searchUsers()方法</a> </body></html>
<%@ page language="java" pageEncoding="GBK"%><%String path = request.getContextPath();%><html> <head> <title>Struts DMI</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"> </head> <body> <a href="userAdd.action">通过普通调用addUser()方法</a> <br/> <a href="userSearch.action">通过普通调用searchUsers()方法</a> <hr> <a href="user!addUser.action">通过DMI方式调用addUser()方法</a> <br/> <a href="user!searchUsers.action">通过DMI方式调用searchUsers()方法</a> </body></html>