Struts2返回json

<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; }






原文地址:https://www.cnblogs.com/yutingliuyl/p/6873910.html