Structs2中Action接口非常的重要,在struts.xml配置中根据对应的action的名字匹配对应的类处理,如果class没写,则默认使用ActionSopport类执行execute方法
,返回success字符串,做出相应的处理。Action的创建有大体上有3种方式,
1:创建一个普通类,里面可以没execute方法,但是必须实现方法返回字符串,否则接收端无法接收对应的参数做出相应的处理。2:写一个类继承自ActionSupport,由于ActionSupport类已经实现了Action方法,所以这样的写法一般是重写ActionSupport类中的execute方法
3:定义一个类直接实现Action接口,实现里面的execute接口
那么,Action的方法调用又是怎么的呢,总体来说也可以分为3种:
1:直接调用execute方法
2:通过method属性配置要调用的adction方法,eg:
在前台约定好了action的名字
处理端:
在action 中通过通配符*匹配对应的字段,并且交给包名为com.yc.web.actions.StudentAction中的方法为*(),也就是reg()方法做出相应的处理。
3:DMI动态调用方法,但是官方文档说了,其实是不推荐这种方法,原因有2个:1:通过这种方式调用的Action的话,会暴露对应的bean类,会影响到项目的安全性
2:会覆盖structs1中传入的想通配符等属性。
如果实在要用的话,也是很简单,现在stucts.xml中将默认动态方法调用属性设置为true,eg:
然后在前段页面如下:
struts.xml配置文件如下:
PersonAction类如下:
package com.yc.web.actions;
import java.util.Random;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
/**
* ActionSupport是实现了Action接口的类,它对execute()方法做了一个简单的实现,即返回success
* 那我们就需要重写execute()以实现不同的返回
* @author feng
*
*/
public class PersonAction extends ActionSupport{
public String execute(){
System.out.println("访问了PersonAction的execute方法");
Random r=new Random();
int result=r.nextInt(2);
if(result==0){
return "faild";
}else{
return "success";
}
}
/**
* 通过通配符来实现severlet的的op转发功能,如果没有匹配的方法则直接报出找不到方法的异常
* @return
*/
public String add(){
System.out.println("访问了PersonAction的add方法");
return Action.SUCCESS;
}
public String delete(){
System.out.println("访问了PersonAction的delete方法");
return Action.SUCCESS;
}
public String update(){
System.out.println("访问了PersonAction的update方法");
return Action.SUCCESS;
}
public String find(){
System.out.println("访问了PersonAction的find方法");
return Action.SUCCESS;
}
}
然后就能匹配上去并访问对应的方法,根据返回的字符串,做出对对应页面的跳转。