---
title: "《研磨struts2》第十四章 对Ajax的支持 之 14.4 使用JSON插件 "
author: "研磨struts2"
date: "2012-06-05T14:18:40Z"
tags: []
categories: ["企业架构"]
slug: "struts2-ajax-14-4-json"
draft: false
lastmod: "2012-06-05T14:18:40Z"
id: 1551885
url: "https://rubbing-struts2.iteye.com/blog/1551885"
---

## 14.4  使用JSON插件

### []()14.4.1 JSON基础

JSON（JavaScript Object Natation），它是一种轻量级、基于文本、语言无关的数据交换格式，类似于XML，是一种结构化数据串行化的文本格式，常常用于服务器与JavaScript之间的数据交换上。

       JSON是从ECMAScript语言标准衍生而来的，定义了一套简单的格式化规则，JSON可以描述四种简单的类型，包括字符串、数字、布尔值及和null；还可以描述两种结构化类型，包括对象和数组。

       当然，更多JSON具体的语法不是这里关注的重点，有需要的朋友请参见http://json.org/，在那里可以获取更多的JSON的知识。

### []()14.4.2 JSON插件

为了更容易使用JSON，Struts2提供了JSON插件，这个插件提供了名为“json”的ResultType，如果设置某个Result的类型为json，那么JSON插件会把这个Action对象序列化成为一个json格式的字符串，然后再向客户端返回这个字符串。

       要使用JSON插件，只需要把struts2-json-plugin-2.1.8.1.jar文件拷贝到WEB-INF/lib里面即可。

       JSON插件提供了一些参数，供大家在有需要的时候选用，可以通过他们实现更精确的控制，基本的参数罗列如下：

- excludeProperties：输出结果需要去除的属性值，支持正则表达式匹配属性名，可以用“,”分割填充多个正则表达式。如下示例代码就表示，user属性里面的password属性不会被序列化输出，代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4132.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4132.html)[打印](http://sishuok.com/forum/blogPost/list/4132.html)

1. &lt;result type="json"&gt;
2. &lt;param name="excludeProperties"&gt;
3. user.password
4. &lt;/param&gt;
5. &lt;/result&gt;

includeProperties：输出结果中需要包含的属性值，支持正则表达式和属性名匹配，可以用“,”分割填充多个正则表达式。如下示例就表示输出user的所有属性，代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4132.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4132.html)[打印](http://sishuok.com/forum/blogPost/list/4132.html)

1. &lt;result type="json"&gt;
2. &lt;param name="includeProperties"&gt;
3. user.*
4. &lt;/param&gt;
5. &lt;/result&gt;

root：根据ognl表达式取出你需要输出的结果的根对象，如下示例就表示输出user的name属性的值，代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4132.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4132.html)[打印](http://sishuok.com/forum/blogPost/list/4132.html)

1. &lt;result type="json"&gt;
2. &lt;param name="includeProperties"&gt;
3. user.name
4. &lt;/param&gt;
5. &lt;/result&gt;

<!--THE END-->

- excludeNullProperties：表示是否去掉空值， 默认值是false，如果设置为true会自动将为空的值过滤，只输出不为空的值
- ignoreHierarchy：表示是否忽略继承关系，默认值是true，也就是在输出的时候不会自动把父级对象序列化并输出。

当然，JSON插件还有很多的参数，这里就不去一一罗列了，有兴趣的朋友请参见https://cwiki.apache.org/confluence/display/WW/JSON%20Plugin，哪里有详尽的参数说明。

### 14.4.3使用JSON插件来实现Ajax

       沿用前面演示Ajax的示例，实现最常见的输入校验的功能，通过Ajax来判断输入的ID是否重复，并给出相应的提示信息。

（1）Action的写法跟以前差不多，示例代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4132.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4132.html)[打印](http://sishuok.com/forum/blogPost/list/4132.html)

01. public class AjaxAction extends ActionSupport {
02. private String account;
03. private String password;
04. private String msg;
05. public String getAccount() {
06. return account;
07. }
08. public void setAccount(String account) {
09. this.account = account;
10. }
11. public String getPassword() {
12. return password;
13. }
14. public void setPassword(String password) {
15. this.password = password;
16. }
17. public String getMsg() {
18. return msg;
19. }
20. public void setMsg(String msg) {
21. this.msg = msg;
22. }
23. public String execute() throws Exception {
24. //准备已经注册的数据,测试使用
25. Set&lt;String&gt; set = new HashSet&lt;String&gt;();
26. set.add("account1");
27. set.add("account2");
28. set.add("account3");
29. if(set.contains(account)){
30. msg = "输入不正确，请重新输入";
31. }else{
32. msg = "输入正确";
33. }
34. return this.SUCCESS;
35. }
36. }

注意：Action的属性需要提供getter/setter方法，不能用public属性的方式进行值的对应，否则JSON插件是不会正确序列化属性值的。

（2）struts.xml的配置有一些变化，首先是不再继承struts-default，而是改为继承json-default；其次result的type要设置为json，示例代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4132.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4132.html)[打印](http://sishuok.com/forum/blogPost/list/4132.html)

1. &lt;action name="ajaxAction" class="cn.javass.ajax.AjaxAction"&gt;
2. &lt;result name="success" type="json"&gt;&lt;/result&gt;
3. &lt;/action&gt;

（3）页面也有一些变化，主要是在获取Action的返回值过后，需要通过eval方法来把json字符串造型成为一个对象，然后把这个对象中的msg属性的值设置到div中显示即可，示例代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4132.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4132.html)[打印](http://sishuok.com/forum/blogPost/list/4132.html)

01. &lt;%@ page contentType="text/html; charset=gb2312"%&gt;
02. &lt;head&gt;&lt;meta http-equiv="Content-Type" content="text/html;charset=gb2312"&gt;&lt;/head&gt;
03. &lt;script language="javascript"&gt;
04. var myRequest;
05. function t1(){
06. //准备向后台传输的数据
07. var account = document.getElementById("account").value;
08. //Ajax
09. myRequest = new ActiveXObject("Msxml2.XMLHTTP");
10. myRequest.onreadystatechange = t2;
11. myRequest.open("GET","ajaxAction.action?account="+account,true);
12. myRequest.send(null);
13. }
14. function t2(){
15. if(myRequest.readyState==4){
16. var ret = myRequest.responseText;
17. //把json造型成对象
18. var obj = eval("("+ret+")");
19. //后续处理，把对象的msg设置到div中显示出来
20. document.all("myDiv").innerHTML = obj.msg;
21. }
22. }
23. &lt;/script&gt;
24. &lt;form action="" medhot="post"&gt;
25. &lt;table&gt;
26. &lt;tr&gt;
27. &lt;td colspan=3 align=center&gt;新用户注册&lt;/td&gt;
28. &lt;/tr&gt;
29. &lt;tr&gt;
30. &lt;td&gt;用户帐号：&lt;/td&gt;
31. &lt;td&gt;&lt;input type="text" id="account" name="account" onblur="t1();"&gt;&lt;font color=red&gt;\*&lt;/font&gt;&lt;/td&gt;
32. &lt;td&gt;&lt;div id="myDiv"&gt;&lt;/div&gt;&lt;/td&gt;
33. &lt;/tr&gt;
34. &lt;tr&gt;
35. &lt;td&gt;用户密码：&lt;/td&gt;
36. &lt;td colspan=2&gt;&lt;input type="password" id=""password" name="password"&gt;&lt;/td&gt;
37. &lt;/tr&gt;
38. &lt;tr&gt;
39. &lt;td&gt;重复密码：&lt;/td&gt;
40. &lt;td colspan=2&gt;&lt;input type="password" id=""password2" name="password2"&gt;&lt;/td&gt;
41. &lt;/tr&gt;
42. &lt;tr&gt;
43. &lt;td colspan=3 align=center&gt;&lt;input type="submit" value="保存注册信息"&gt;&lt;/td&gt;
44. &lt;/tr&gt;
45. &lt;/table&gt;
46. &lt;/form&gt;

去运行看看，效果应该跟前面AJAX演示的效果是一样的。

 

私塾在线网站原创《[研磨struts2](http://sishuok.com/forum/blogCategory/showByCategory.html?categories_id=81&user_id=5948)》系列

转自请注明出处：【[http://sishuok.com/forum/blogPost/list/0/4132.html](http://sishuok.com/forum/blogPost/list/0/4132.html)】

欢迎访问[http://sishuok.com](http://sishuok.com/)获取更多内容