1.动态action
动态action处理方式通过请求Action对象中一个具体方法来实现动态操作,格式:userAction!add,请求其add()方法
下面通过一个简单的实例了解动态action和action的method属性。
创建FirstStruts类继承ActionSupport类,创建属性info并为其提供getter()和setter()方法
package com.gyj.struts;
import com.opensymphony.xwork2.ActionSupport;
public class FirstStruts extends ActionSupport {
private String info;
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String add()throws Exception{
setInfo("添加用户信息");
return "add";
}
public String update()throws Exception{
System.out.println("update");
setInfo("修改用户信息");
return "update";
}
public String delete()throws Exception{
setInfo("删除用户信息");
return "delete";
}
}
index.jsp页面<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="FirstStruts1">add</a>
<a href="FirstStruts2">delete</a>
<a href="FirstStruts!update">update</a>
</body>
</html>
action对象处理后返回结果 first.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%> //使用Struts2标签必须加此代码
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:property value= "info"/>
</body>
</html>
在web.xml文件中声明过滤器
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
struts.xml文件配置
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<package name="myPackage" extends="struts-default" namespace="/">
<!-- 动态调用action -->
<action name="FirstStruts" class = "com.gyj.struts.FirstStruts">
<result name = "update">/first.jsp</result>
</action>
<!-- action method调用 -->
<action name="FirstStruts1" class = "com.gyj.struts.FirstStruts" method = "add">
<result name = "add">/first.jsp</result>
</action>
<action name="FirstStruts2" class = "com.gyj.struts.FirstStruts" method = "delete">
<result name = "delete">/first.jsp</result>
</action>
</package>
</struts>
动态action运行成功需要在Struts标签中添加属性<constant name="struts.enable.DynamicMethodInvocation" value="true" />将struts.enable.DynamicMethodInvocation设置为true才能运行。