Struts2 + JSON to achieve the return of objects and a list of AJAX

JSON is a plug-in, it allows us to call in the asynchronous JavaScript in Action, it provides a return json result type (ResultType), as long as the specified type for Action

return json result type, then the outcome of this response does not need to return to any view layer, JSON to Action in the sequence status information into a prescribed format JSON data and return the data

To JAVASCRIPT, to be completed this interactive AJAX applications.
JSON plug-ins to the application, first of all need to

http://code.google.com/p/jsonplugin/downloads/list

Download the latest plug-in JSON, I was here to download jsonplugin –

0.33.jar, the document Kaodao LIB directory WEB project, of course, also need to download Struts2 libraries, can http://struts.apache.org/download.cgi # struts2014

Here to download, extract after download, the WEB project JAR Kaodao LIB directory, should not be less than the following JAR file (struts2-api-2.0.5.jar, struts2-core-2.0.5.jar,

ognl-2.6.9.jar, xwork-2.0.0.jar, commons-logging-1.1.jar, freemarker-2.3.8.jar, depending on the specific version of the file name may be), then we can write in an application

To test, divided into the two-step routines to write, the first step to achieve the return of a result object, the second step to achieve returns a results list, first of all look at the results back to the realization of the object.
We need to create a JavaBean for the value object to the user’s basic data package into the entity objects and results in the results list will be used to
Users.java code is as follows:

package com.jsontostruts2.vo;

/**
 * <p>
 * 创 建 人:ChenTao
 * <p>
 * 创建日期:2009-5-18 下午05:24:48
 * <p>
 */
public class Users {

	private Integer userId;

	private String userName;

	private String sex;

	public Users() {

	}
	// get... set.... 略......
}

UserAction.java source to achieve the following:

package com.jsontostruts2.action;

import com.googlecode.jsonplugin.annotations.JSON;
import com.jsontostruts2.vo.Users;
import com.opensymphony.xwork2.ActionSupport;

/**
 * <p>
 * 创 建 人:ChenTao
 * <p>
 * 创建日期:2009-5-18 下午05:22:50
 * <p>
 */
@SuppressWarnings("serial")
public class UserAction extends ActionSupport {

	private Users users;

	@JSON(name="USER")
	public Users getUsers() {
		return users;
	}

	public void setUsers(Users users) {
		this.users = users;
	}

	@Override
	public String execute() throws Exception {
		users = new Users();
		users.setUserId(1);
		users.setUserName("ctojxzsycztao");
		users.setSex("男人");
		return SUCCESS;
	}

}

Next, we need to configure struts.xml paper is the following in order to write the document will not repeat here I will list the results of the request object and control贴上来together, the content of the document:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<!-- 注意这里扩展不再是 struts-default,而是 json-default -->
	<package name="jsonManager" extends="json-default">
		<!-- 返回结果类型为 json -->
		<action name="userJson">
			<result type="json"/>
		</action>
		<!-- 该action在返回列表时添加进来的 -->
		<action name="jsonlist">
			<result type="json"/>
		</action>

	</package>
</struts>

An ability to create web.xml and userjson.jsp:

web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<filter>
		<filter-name>Struts2</filter-name>
		<filter-class>
			org.apache.struts2.dispatcher.FilterDispatcher
		</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>Struts2</filter-name>
		<url-pattern>*.action</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>Struts2</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

userjson.jsp:

<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>json 返回对象处理</title>
	<script language="javascript">
		var xmlHttp = false;
		try{
			xmlHttp = new ActiveXObject("msxml2.XMLHTTP");
		}catch(e1){
			try{
				xmlHttp = new ActiveXObject("microsoft.XMLHTTP");
			}catch(e2){
				try{
					xmlHttp = new XMLHttpRequest();
				}catch(e3){
					xmlHttp = false;
				}
			}
		}
		if(!xmlHttp){
			alert("create xmlHttpRequest fail");
		}
		function jsonResult(){
			xmlHttp.onreadystatechange = function(){
			    if(xmlHttp.readyState == 4) {
				// 将 JSON 对象转换为JSON字符串,需要注意调用eval函数时必须使用"("和")"将JSON字符串括起来,否

则会出错
				var userObj = eval('(' + xmlHttp.responseText + ')');
				var userStr = "<table border=0>";
                    userStr += '<tr><td><b>userId</b></td><td>' + userObj.USER.userId + '</td></tr>';
                    userStr += ('<tr><td><b>userName</b></td><td>' + userObj.USER.userName + '</td></tr>');
                    userStr += ('<tr><td><b>sex</b></td><td>' + userObj.USER.sex + '</td></tr>');
                    userStr += "</table>";
                    document.getElementById('jsonDiv').innerHTML = userStr;
                }
			}
			xmlHttp.open("POST","userJson.action",true);
			xmlHttp.send(null);
		}
	</script>
  </head>
  <body>
  	<div></div>
    <input type="button" value="show">
  </body>
</html>

Now you can release will be applied to your containers which enter http://localhost:8080/struts2ToJson/userjson.jsp Point show, this time you can see the node you want

Fruit, and then return the list to achieve the practice, of course, with the return of objects will be different, we need to convert a List object as a JSON string specification can be sent to the client after the JS,

First of all, the establishment of a specified string into a List of tools, the tool is in an unintentionally brought from the Internet to see spent on, after a little modification, in order to reduce the number of lines of code, I will only paste

Applicable to the sample code:
JsonUtil.java:

package com.jsontostruts2.util;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.List;

/**
 * <p>
 * @author ChenTao
 * <p>
 * @Date 2009-5-18 下午05:47:27
 * <p>
 */
public class JsonUtil {

	/**
	 * @param object
	 *            任意对象
	 * @return java.lang.String
	 */
	public static String objectToJson(Object object) {
		StringBuilder json = new StringBuilder();
		if (object == null) {
			json.append("\"\"");
		} else if (object instanceof String || object instanceof Integer) {
			json.append("\"").append((String)object).append("\"");
		} else {
			json.append(beanToJson(object));
		}
		return json.toString();
	}

	/**
	 * 功能描述:传入任意一个 javabean 对象生成一个指定规格的字符串
	 * 
	 * @param bean
	 *            bean对象
	 * @return String
	 */
	public static String beanToJson(Object bean) {
		StringBuilder json = new StringBuilder();
		json.append("{");
		PropertyDescriptor[] props = null;
		try {
			props = Introspector.getBeanInfo(bean.getClass(), Object.class)
					.getPropertyDescriptors();
		} catch (IntrospectionException e) {
		}
		if (props != null) {
			for (int i = 0; i < props.length; i++) {
				try {
					String name = objectToJson(props[i].getName());
					String value = objectToJson(props[i].getReadMethod().invoke(bean));
					json.append(name);
					json.append(":");
					json.append(value);
					json.append(",");
				} catch (Exception e) {
				}
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	/**
	 * 功能描述:通过传入一个列表对象,调用指定方法将列表中的数据生成一个JSON规格指定字符串
	 * 
	 * @param list
	 *            列表对象
	 * @return java.lang.String
	 */
	public static String listToJson(List<?> list) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (list != null && list.size() > 0) {
			for (Object obj : list) {
				json.append(objectToJson(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}
}

UserListAction.java:

package com.jsontostruts2.action;

import java.util.ArrayList;
import java.util.List;

import com.googlecode.jsonplugin.annotations.JSON;
import com.jsontostruts2.util.JsonUtil;
import com.jsontostruts2.vo.Users;
import com.opensymphony.xwork2.ActionSupport;

/**
 * <p>
 * 创 建 人:ChenTao
 * <p>
 * 创建日期:2009-5-18 下午05:45:42
 * <p>
 */
@SuppressWarnings("serial")
public class UserListAction extends ActionSupport {

	/* 用于存放JSON生成后的字符串结果 */
	private String jsonResult;

	@JSON(name="JSONRESULT")
	public String getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(String jsonResult) {
		this.jsonResult = jsonResult;
	}

	@Override
	public String execute() throws Exception {
		List<Users> userList = new ArrayList<Users>();
		Users users = new Users();
		users.setUserId(1);
		users.setUserName("ctojxzsycztao");
		users.setSex("男人");
		userList.add(users);
		users = null;
		users = new Users();
		users.setUserId(2);
		users.setUserName("rain");
		users.setSex("女人");
		userList.add(users);
		users = null;
		users = new Users();
		users.setUserId(3);
		users.setUserName("mimi");
		users.setSex("女人");
		userList.add(users);
		jsonResult = JsonUtil.listToJson(userList);
		System.out.println(jsonResult);
		return SUCCESS;
	}
}

Next will be to write a jsonList.JSP the results page for users is

<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>json 返回列表处理</title>
	<script language="javascript">
		var xmlHttp = false;
		try{
			xmlHttp = new ActiveXObject("msxml2.XMLHTTP");
		}catch(e1){
			try{
				xmlHttp = new ActiveXObject("microsoft.XMLHTTP");
			}catch(e2){
				try{
					xmlHttp = new XMLHttpRequest();
				}catch(e3){
					xmlHttp = false;
				}
			}
		}
		if(!xmlHttp){
			alert("create xmlHttpRequest fail");
		}
		function jsonListResult(){
			xmlHttp.onreadystatechange = function(){
			    if(xmlHttp.readyState == 4) {
					var userList = eval('(' + xmlHttp.responseText + ')');
					var user = eval(userList.JSONRESULT);
					var result = "<table border=0>";
					result += "<tr><td>userId</td><td>userName</td><td>sex</td></tr>";
					for(var i=0;i<user.length;i++) {
						result += "<tr>";
						result += "<td>"+user[i].userId +"</td>";
						result += "<td>"+user[i].userName+"</td>";
						result += "<td>"+user[i].sex+"</td>";
						result += "</tr>";
					}
					result += "</table>";
                    document.getElementById('jsonDiv').innerHTML = result;
                }
			}
			xmlHttp.open("POST","jsonlist.action",true);
			xmlHttp.send(null);
		}
	</script>
  </head>
  <body>
  	<div></div>
    <input type="button" value="show list">
  </body>
</html>

Will now be deployed to the WEB project repeat containers, start: in the browser, type http://localhost:8080/struts2ToJson/jsonList.jsp Points show list button to see the results of

Is correct, if incorrect please refer to the routines to see if there is no missing part is not configured into the code in the above we have to see @ JSON Notes, the Notes can be changed to return the results of JSON property name, so the wrote the article on here, friends need to download the sample can be downloaded in the annex, which contains the source code of the article and the corresponding JAR