日期:2014-05-16  浏览次数:20399 次

使用Struts2+Gson+JQuery实现异步请求JSON对象
GSON是Google公司的Java对象序列化成JSON的插件
下载地址:http://code.google.com/p/google-gson/downloads/list
下载下来以后:把gson-1.4.jar这个jar文件加到工程里。
Action的使用方式是:
package test.gson;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;

public class TestGson extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private Users user;
	public Users getUser() {
		return user;
	}
	public void setUser(Users user) {
		this.user = user;
	}
	@Override
	public String execute() throws Exception {
		user = new Users();
		user.setId(10000);
		user.setUserName("zhangsan");
		user.setPwd("000000");
		user.setEmail("zhangsan@sina.com");
		
		Gson g  = new Gson();
		String json = g.toJson(user);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8");
		response.setHeader("Cache-Control","no-cache");
		
		PrintWriter pw = response.getWriter();
		pw.print(json);
		pw.flush();
		pw.close();
		
		
		return null;
	}
}

其中response.setContentType("application/json;charset=utf-8");是最重要的
一定要把ContentType设置成application/json形式
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<package name="jsons" extends="struts-default" namespace="/">
		<action name="testGson" class="test.gson.TestGson"></action>
	</package>
</struts>

Gson其实可以用在所有的Javaweb工程了,不一定是Struts2