Action类
一、实现方式
1、POJO,普通类
2、Action接口,实现接口
![](https://i-blog.csdnimg.cn/blog_migrate/98503aa476b0aec0aa7f17321bb6988f.png)
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";
public String execute() throws Exception;
success : 表示成功了。
none:没有返回值。相当方法void。没有返回值表示没有result,常用与ajax操作。使用response发送数据。
error:服务器异常。
input:表示用户输入错误。
login:表示需要权限。
action:
package cn.hcx.e_action;
import com.opensymphony.xwork2.Action;
public class Demo1Action implements Action {
public String execute() throws Exception {
//如果不需要返回结果,就返回none
//return NONE
System.out.println("action_Demo1Action");
return SUCCESS;
}
}
原本的:
<struts>
</package>
<package name="ns2" namespace="/b" extends="struts-default" >
<action name="Demo2Action" class="cn.hcx.d_namespace.Demo2Action" method="execute" >
<result name="success" type="dispatcher" >/index.jsp</result>
</action>
</package>
</struts>
实现了action接口后:
<struts>
<!-- 常量的包 -->
<package name="action" namespace="/action" extends="struts-default" >
<!-- 可以不配置method属性,如果不配置默认走execute方法 -->
<action name="Demo1Action" class="cn.hcx.e_action.Demo1Action" >
<!-- 可以不配置name属性,如果不配置默认走 "success" -->
<result type="dispatcher" >/index.jsp</result>
</action>
<action name="Demo2Action" class="cn.hcx.e_action.Demo2Action" >
<!-- 可以不配置name属性,如果不配置默认走 "success" -->
<result type="dispatcher" >/index.jsp</result>
</action>
<!-- class属性也可以不配置. 如果不配置走 com.opensymphony.xwork2.ActionSupport -->
<action name="Demo3Action">
<!-- type属性也可以不配置,默认 就是dispatcher 以下是依据:
<result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/>
-->
<result >/index.jsp</result>
</action>
</package>
</struts>
3. ActionSupport类,继承类
![](https://i-blog.csdnimg.cn/blog_migrate/153b35a48fffc94fa42e133fcd0ac878.png)
继承:已经默认提供很多功能。
package cn.hcx.e_action;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
public class Demo2Action extends ActionSupport {
}
二、方法
public String execute(){
return SUCCESS;
}
1必须是public
2建议有返回值,类型必须String
3方法名称自定义
4没有参数
5需要throw Exception
6非静态的
注意:可以没有返回值,一般情况都有,可以使用return "none" 表示没有返回。
public void add() throw Exception{
}
三、Struts.xml中struts-default包中的默认配置
如果不手动配置Action 默认Action如下配置:
<default-class-refclass="com.opensymphony.xwork2.ActionSupport" />
如果不配置结果的type属性,默认type属性如下配置:
<result-type name="dispatcher"class="org.apache.struts2.dispatcher.ServletDispatcherResult"default="true"/>