三大框架(ssh)学习——Action接口

Action详解和配置

Struts1中的action需要实现特定的接口。Struts2中的Action相当的灵活,既可以实现接口、也可以不实现而只是个普通java类。就像我们前面写的helloworld程序一样。

不继承任何类的Action

这种方式的好处是,我们写的Action类完全不和struts2框架发生耦合,代码不依赖struts2的类库。当然,弊端也比较明显不能使用struts2中的某些功能。代码如下:

package com.bjsxt.struts.test;

 

public class FirstAction {

 

private String msg;

 

public String execute() throws Exception{

System.out.println("FirstAction.test1()");

setMsg("为了让生活美好!");

return "success";

}

 

public String getMsg() {

return msg;

}

 

public void setMsg(String msg) {

this.msg = msg;

}

}

 

实现Action接口

Struts2的Action接口中只定义了execute方法和几个预定义的常量。代码如下:

package com.opensymphony.xwork2;

public interface 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";

 

    public String execute() throws Exception;

}

开发中,我们尽量使用Action接口中预定义的常量,实现规范编程。如下为我们改版的Action类代码:

package com.bjsxt.struts.test;

 

import com.opensymphony.xwork2.Action;

 

public class FirstAction implements Action {

 

private String msg;

 

public String execute() throws Exception{

System.out.println("FirstAction.test1()");

setMsg("为了让生活美好!");

return SUCCESS;  //直接使用接口中的常量

}

 

public String getMsg() {

return msg;

}

 

public void setMsg(String msg) {

this.msg = msg;

}

}

继承ActionSupport类

ActionSupport类实现了Action接口,我们自定义的Action类一般都采用继承ActionSupport类的方式。使用ActionSupport的好处是我们可以直接使用这个类中已经定义好的方法。

代码如下:

package com.bjsxt.struts.test;

 

import com.opensymphony.xwork2.ActionSupport;

 

public class FirstAction extends ActionSupport {

 

private String msg;

 

public String execute() throws Exception{

System.out.println("FirstAction.test1()");

setMsg("为了让生活美好!");

return SUCCESS;

}

 

public String getMsg() {

return msg;

}

 

public void setMsg(String msg) {

this.msg = msg;

}

}

Action中自定义方法和通过URI动态执行(DMI)

Action中可以定义多个任意名称的方法,不是只有execute方法。我们为Action增加test2方法:

public String test2() throws Exception {

System.out.println("FirstAction.test2()");

setMsg("刚刚调用了test2方法!");

return SUCCESS;

}

通过DMI(Dynamic  Method  Invoke)动态方法调用,我们可以通过URL即可调用相应的方法,相当方便。格式为:actionname!methodname

 

地址栏输入:http://localhost/teststruts/first!test2 

控制台输出:FirstAction.test2()

页面显示:

猜你喜欢

转载自blog.csdn.net/weixin_38003467/article/details/83544937
今日推荐