struts2 - 2 struts2 Action类的三种访问方式

Struts2 的action类有三种访问方式:传统访问,通配符访问以及动态访问。主要在struts.xml文件中设置

详见代码:

  • 请求页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>Action</h3>
	<a href="${pageContext.request.contextPath}/hello.action">helloAction</a><br/>
	<a href="${pageContext.request.contextPath}/actionDemo1.action">actionDemo1</a><br/>
	<a href="${pageContext.request.contextPath}/actionDemo2.action">actionDemo2</a><br/>
	<h3>Action的访问方式</h3>
	<a href="${pageContext.request.contextPath}/act_nomual.action">传统访问</a><br/>
	<a href="${pageContext.request.contextPath}/act_actMethod1.action">通配符访问</a><br/>
	<a href="${pageContext.request.contextPath}/actionDemo!actMethod1.action">动态访问</a><br/>
</body>
</html>
  • Action类
package action;

import com.opensymphony.xwork2.ActionSupport;

public class ADctionDemo3 extends ActionSupport{

	private static final long serialVersionUID = 1211686654382520011L;
	
	public String actMethod1() {
		
		System.out.println("执行" + this.getClass().getSimpleName()+ ":" +
				new Exception().getStackTrace()[0].getMethodName());
		
		return this.SUCCESS;
		
	}
	
	public String actMethod2() {
		
		System.out.println("执行" + this.getClass().getSimpleName()+ ":" +
				new Exception().getStackTrace()[0].getMethodName());
		
		return this.SUCCESS;
		
	}
	
	
	
}
  • 配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

	
	 <!-- 开启动态访问action -->
	 <constant name="struts.enable.DynamicMethodInvocation" value="true"/>

	<!-- 包结构 -->
        <package name="default" namespace="/" extends="struts-default">
    	
		
		<!-- 传统的访问模式 -->
		<action name="act_nomual" class="action.ADctionDemo3" method="actMethod1">
			<result name="success">/retMsg.jsp</result>
		</action>
		<!-- 
			通过通配符来访问
			name中第一个*与method大括号中1匹配,如果有第二个* 则匹配2
			通过这种方式获得页面中的方法名,执行action类中相同的方法。
		 -->
		<action name="act_*" class="action.ADctionDemo3" method="{1}">
			<result name="success">/retMsg.jsp</result>
		</action>
		
		<!-- 
			动态访问
			需要开启动态访问,设置常量struts.enable.DynamicMethodInvocation 为true
		 -->
		<action name="actionDemo" class="action.ADctionDemo3">
			<result name="success">/retMsg.jsp</result>
		</action>
		
    </package>
    <!-- 
		通过这种方式来分包处理配置文件,不过现实中可能用的不多    
	    <include file="testPackage/sturts_test.xml"></include>
     -->
	
</struts>

猜你喜欢

转载自blog.csdn.net/alexzt/article/details/82802881
今日推荐