Struts2 Action的3种创建方式

 

Action是Strut2的核心内容,相当于Servlet,用于处理业务。

Action是一个Java类,直接新建Java类即可。

 

Action有3种实现方式。

1、使用POJO,设置成员变量,写对应的setter、getter方法,再写一个返回值是String的方法来处理业务逻辑,并把<action>的method属性值设置为此方法。

POJO:普通的、传统的Java对象(类),不实现任何接口,不继承任何类。

此种方式创建的Action不与其他类、接口耦合,是低侵入式的。

但此种方式并不常用,因为要从头开始写,自己敲public String xxx(){     },还要在struts.xml中指定要调用的方法,太麻烦了。

 

 

 

2、实现Action接口

import com.opensymphony.xwork2.Action;

public class XxxAction implements Action {
    @Override
    public String execute() throws Exception {
        return null;
    }
}

默认会调用execute()方法来处理请求,不必在structs.xml中配置所调用的方法。

 

Action接口内置了一些常用的字符串常量,我们可以直接使用:

 String SUCCESS = "success";
    String NONE = "none";
    String ERROR = "error";
    String INPUT = "input";
    String LOGIN = "login";

 

注意是 com.opensymphony.xwork2.Action,导包时不要导错了。

 

 

3、继承ActionSupport类

public class XxxAction extends ActionSupport {
    @Override
    public String execute() throws Exception {
        return null;
    }
}

ActionSupport类实现了Action接口,具有Action接口的所有功能,且实现了Serializable等其它接口,功能更加强大。

 

 

一般使用第三种方式。

 

 

在structs-default.xml提供的默认的包配置中:

        <default-class-ref class="com.opensymphony.xwork2.ActionSupport" />

        <global-allowed-methods>execute,input,back,cancel,browse,save,delete,list,index</global-allowed-methods>

默认会预先实例化ActionSupport,且execute是默认调用的方法之一。

 

posted @ 2019-09-03 17:24  chy_18883701161  阅读(646)  评论(0编辑  收藏  举报