JSON 是一个插件,它允许我们在JavaScript中异步调用Action,它提供了一个json的返回结果类型(ResultType),只要为Action指定类型为
json返回结果类型,那么这个响应结果不需要返回给任何视图层,JSON会将Action里的状态信息序列化为JSON指定格式的数据,并将该数据返回
给JAVASCRIPT,这样可以完成AJAX的应用交互.
要应用 JSON 插件,首先需要到
http://code.google.com/p/jsonplugin/downloads/list
下载最新JSON插件,我这里下载的是jsonplugin-
0.33.jar ,将该文件拷到WEB工程的LIB目录,当然还需要下载Struts2 类库,可以到http://struts.apache.org/download.cgi#struts2014
这里去下载,下载完后解压缩,将JAR拷到WEB工程的LIB目录,不能少于以下几个JAR文件(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,具体文件名视版本而定),接下来我们可以写个应用
来试验,本例程分为二步来写,第一步实现返回一个结果对象,第二步实现返回一个结果列表,首先来看下返回结果对象的实现.
我们需要先建立一个JavaBean 为值对象,用来将用户的基本数据封装进去,该实体在结果对象和结果列表中都会使用到
Users.java 代码如下:
- package com.jsontostruts2.vo;
-
-
-
-
-
-
-
-
- public class Users {
-
- private Integer userId;
-
- private String userName;
-
- private String sex;
-
- public Users() {
-
- }
-
- }
实现 UserAction.java 源码如下:
- package com.jsontostruts2.action;
-
- import com.googlecode.jsonplugin.annotations.JSON;
- import com.jsontostruts2.vo.Users;
- import com.opensymphony.xwork2.ActionSupport;
-
-
-
-
-
-
-
-
- @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;
- }
-
- }
接下来我们需要配置 struts.xml 文件,为了在现下面不再重复写该文件,这里我将结果对象和列表的请求控制一并贴上来,文件内容:
- <?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>
-
- <package name="jsonManager" extends="json-default">
-
- <action name="userJson" class="com.jsontostruts2.action.UserAction">
- <result type="json"/>
- </action>
-
- <action name="jsonlist" class="com.jsontostruts2.action.UserListAction">
- <result type="json"/>
- </action>
-
- </package>
- </struts>
能后创建web.xml 和 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 id="jsonDiv"></div>
- <input type="button" value="show" onclick="jsonResult();">
- </body>
- </html>
现在你可以将应用发布到你的容器当中输入 http://localhost:8080/struts2ToJson/userjson.jsp 点show,这个时候你可以看到你想要的结
果,接来实现下返回列表的做法,当然与返回对象会有所不同,我们需要将一个List对象转换为一个JSON规范的字符串,能后发送给客户端的JS,
首先建立一个将List 转换为指定字符串的工具类,该工具是在一个无意间从网上看到就拿来用了,经过少许修改,为了减少代码行数我将只贴
出适用于本示例的代码:
JsonUtil.java :
- package com.jsontostruts2.util;
-
- import java.beans.IntrospectionException;
- import java.beans.Introspector;
- import java.beans.PropertyDescriptor;
- import java.util.List;
-
-
-
-
-
-
-
-
- public class JsonUtil {
-
-
-
-
-
-
- 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();
- }
-
-
-
-
-
-
-
-
- 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();
- }
-
-
-
-
-
-
-
-
- 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;
-
-
-
-
-
-
-
-
- @SuppressWarnings("serial")
- public class UserListAction extends ActionSupport {
-
-
- 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;
- }
- }
接下来将要写一个jsonList.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 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 id="jsonDiv"></div>
- <input type="button" value="show list" onclick="jsonListResult();">
- </body>
- </html>
现在将工程重复部署到WEB容器,启动:在浏览器中输入 http://localhost:8080/struts2ToJson/jsonList.jsp 点 show list按钮,看看结果
是否正确,如果不正确请参考本例程,看看有没漏掉部分没有配置进去,在以上代码中我们都有看到 @JSON 的注解,该注解可以改变JSON返回结果的属性名,好了文章就写到这里,需要下载示例的朋友可在附件中下载,里面包含有该文章的源代码和相应的 JAR