struts2中文教程(二) struts2中的action介绍

structs2中的action是一个POJO,不需要继承任何类。相当于一个javaBean。类中定义了私有的属性,以及为属性设置的set及get方法(注:get方法你如果不需要也可以不设)。

下面是一个action中的代码:

 1 public class Tt {
 2     private String username;
 3     private String userpwd;
 4     public void setUsername(String username) {
 5         this.username = username;
 6     }
 7     
 8     public void setUserpwd(String userpwd) {
 9         this.userpwd = userpwd;
10     }
11     
12 }

 

set方法的名字一定要与页面输入域的名字相同。所以页面中的代码必须为

1 <input type="text" name="username" />
2 <input type="text" name="userpwd" />

 

 注意:这里是说的set方法名即setUsername()或 setUserpwd(),而不是私有属性名。属性名与输入域中的名字对应 没有关系。赋值时,先根据页面中请求域中的名字,去寻找对应的set方法,在方法中能为你那个私有属性赋上值即可。介来了理解上的方便,建议属性的名字与页面输入域同名。

     从而看出,struts2中的action已经不再需要struts1.x中的formBean来封装数据了。

     在action中有一个默认的方法如下:

 1 public class Tt {
 2     private String username;
 3     private String userpwd;
 4     public void setUsername(String username) {
 5         this.username = username;
 6     }
 7     
 8     public void setUserpwd(String userpwd) {
 9         this.userpwd = userpwd;
10     }
11     //默认的方法
12     public String execute(){
13         return "success";
14     }
15 }

此方法在赋值并校验完成后自动调用的。

    struts2提供了一个父类,一般开发时都会继承它:com.opensymphony.xwork2.ActionSupport

此类实现了很多接口,例:Action,Validateable接口等。其中有一验证的方法可以重写,以验证客户端数据

 

1 public void validate(){
2     if(null==this.getUsername||"".equals(this.getUsername)){
3         this.addFieldError("输入域名","错误提示");
4     }
5 }

 注释:方法中进行判定,用户名为null或为空,则添加一个错误信息。需要注意的是这种写法:常量写在前面不会出现空指针异常,如果变量写在前面,有可能出现空指针异常的情况,这是一种好的习惯。

      struts2的action的方法返回的是一个String,你可以自己定义这个String,struts2会在配置文件中找到这个String,根据这个String跳转到相应的页面。如果action是继承了ActionSupport,那么就继承了ActionSupport中的几个静态属性:

1 return   ActionSuport.SUCCESS;//返回代表成功的串"success"
2          ActionSupport.ERROR;//返回代表错误的串"error"
3          ActionSupport.NONE;//指execute()执行成功,但不返回视图"none"
4          ActionSupport.INPUT;//验证不成功时返回本串"input"
5          ActionSupport.LOGIN;//没有登录时返回串"login"


posted @ 2009-03-07 17:22  梦飞晨主  阅读(2921)  评论(1编辑  收藏  举报