<span style="font-size:18px;">package com.insuper.action; import com.insuper.service.UserService; import com.insuper.vo.User; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; /** * 注册用户 * * @author seawind * */ public class UserAction extends ActionSupport implements ModelDriven<User> { private String re; private User user = new User(); @Override public User getModel() { return user; } public String getRe() { return re; } public void setRe(String re) { this.re = re; } public String register() throws Exception { System.out.println("注册用户 action 执行... "); userService.addUser(user); this.re="用户注册成功"; return SUCCESS; } private UserService userService; public void setUserService(UserService userService) { this.userService = userService; } } </span>
这是以用户注册为例,需要注意的是一定要有返回值,不能用void方法,否则无法进入Struts拦截器
<span style="font-size:18px;"> <package name="default" namespace="/" extends="json-default"> <!-- 方式一,自动向Action 装配 Service --> <action name="register" class="com.insuper.action.UserAction" method="register"> <result type="json"> <param name="root">re</param> </result> </action></span>这里需要注意extends="json-default"
<result type="json"> <!-- 这里指定将被Struts2序列化的属性,该属性在action中必须有对应的getter方法 --> <!-- 默认将会序列所有有返回值的getter方法的值,而无论该方法是否有对应属性 --> <param name="root">dataMap</param> <!-- 指定是否序列化空的属性 --> <param name="excludeNullProperties">true</param> <!-- 这里指定将序列化re中的那些属性 --> <param name="includeProperties">userList.*</param> <!-- 这里指定将要从re中排除那些属性,这些排除的属性将不被序列化,一般不与上边的参数配置同时出现 --> <param name="excludeProperties">SUCCESS</param> </result>
需要注意的是,如果用JSON插件把返回结果定为JSON。而JSON的原理是在ACTION中的get方法都会序列化, 所以前面是get的方法只要没指定不序列化,都会执行。 如果该方法一定要命名为get*(比如实现了什么接口), 那么可以在该方法的前面加注解声明该方法不做序列化。 注解的方式为:@JSON(serialize=false) 除此之外,JSON注释还支持如下几个域: serialize:设置是否序列化该属性 deserialize:设置是否反序列化该属性。 format:设置用于格式化输出、解析日期表单域的格式。例如"yyyy-MM-dd'T'HH:mm:ss"。 //使用注释语法来改变该属性序列化后的属性名 @JSON(name="newName") public String getName() { return this.name; } 需要引入 import com.googlecode.jsonplugin.annotations.JSON; @JSON(serialize=false) public User getUser() { return this.User; } @JSON(format="yyyy-MM-dd") public Date getStartDate() { return this.startDate; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u014000832/article/details/46706483