Struts之Action的创建方式

1.普通类可以当做Action

package zh.action.demo;

/**
 * 普通类
 * @author ZH
 */
public class Action1 {

	public String fun(){
		System.out.println("Action1...fun...");
		return "success";
	}
	
}

2.继承Action接口

package zh.action.demo;

import com.opensymphony.xwork2.Action;

/**
 * 实现Action接口
 * @author ZH
 */
public class Action2 implements Action{

	/**
	 * 重写Action接口的唯一的抽象方法execute()
	 * 可以使用Action接口中的静态常量
	 *	public static final String SUCCESS = "success";
	 *	public static final String NONE = "none";
	 *	public static final String ERROR = "error";  
	 *	public static final String INPUT = "input";
	 *	public static final String LOGIN = "login";
	 */
	
	// 返回NONE常量,等价于没有返回值,也就不需要配置<result>
	public String execute() throws Exception {
		return NONE;
	}
	
	public String fun(){
		System.out.println("Action2...fun...");
		return SUCCESS;
	}
	
}

3.继承ActionSupport类

package zh.action.demo;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 继承ActionSupport类,此类已经实现了Action接口
 * @author ZH
 */
public class Action3 extends ActionSupport{

	public String fun(){
		System.out.println("Action3...fun...");
		return SUCCESS;
	}
	
}

struts.xml文件

<?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>
	
	<constant name="struts.i18n.encoding" value="UTF-8"></constant>
	
	<package name="demo3" namespace="/" extends="struts-default">
		<action name="action1" class="zh.action.demo.Action1" method="fun">
			<result name="success" type="redirect">/index1.jsp</result>
		</action>
		<action name="action2" class="zh.action.demo.Action2" method="fun">
			<result name="success" type="redirect">/index2.jsp</result>
		</action>
		<action name="action3" class="zh.action.demo.Action3" method="fun">
			<result name="success" type="redirect">/index3.jsp</result>
		</action>
	</package>

</struts>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
 <!--  配置Struts的拦截器 -->
  <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>
  
</web-app>

猜你喜欢

转载自blog.csdn.net/qq_41706150/article/details/80962472