struts2.0.11整合jsonplugin0.32的方法。

来源:互联网 发布:罗技m280 m330 知乎 编辑:程序博客网 时间:2024/06/08 16:01

json 用在web开发中服务器端与客户端交互数据非常重要,特别是在流程的Ajax应用中显得重要,这里谈谈在struts2中整合json插件的方法,解放在web开发中不停拼json String的困扰。

 

步骤1:下载Strut2的最小集合包和json的插件包。

Strut2可以再官方网站下载,json插件在http://code.google.com/p/jsonplugin/downloads/list下载,注意版本。

xwork-2.0.4.jar

struts2-core-2.0.11.1.jar

ognl-2.6.11.jar

freemarker-2.3.8.jar

commons-logging-1.0.4.jar

 

jsonplugin-0.32.jar

注意struts2.1以上版本要下载jsonplugin-0.34.jar否则会有问题。

 

将以上包导入工程中,细节就不说了。

 

步骤2:编写输出json的action类,这里举例JsonDemo类。

我的演示类如下:

 

说明一下,使用json插件的好处就是不在去写将Object转换成json的代码了,框架制动为你转换,前提是你的定义的类是个标准的javabean,原始类型除外。具体规范我这里黏贴上官方的英文说明:

 

 

The JSON plugin provides a "json" result type that serializes actions into JSON. The serialization process is recursive, meaning that the whole object graph, starting on the action class (base class not included) will be serialized (root object can be customized using the "root" attribute). If the interceptor is used, the action will be populated from the JSON content in the request, these are the rules of the interceptor:

  1. The "content-type" must be "application/json"
  2. The JSON content must be well formed, see json.org for grammar.
  3. Action must have a public "setter" method for fields that must be populated.
  4. Supported types for population are: Primitives (int,long...String), Date, List, Map, Primitive Arrays, Other class (more on this later), and Array of Other class.
  5. Any object in JSON, that is to be populated inside a list, or a map, will be of type Map (mapping from properties to values), any whole number will be of type Long, any decimal number will be of type Double, and any array of type List.

 

 

步骤3:在struts.xml中配置JsonDemo这个Action。

 

 

这里注意两个问题:

1.extends必须继承于son-default。

2、返回的类型必须为<result type="json"/>

 

步骤4:写测试

这里推荐使用一个客户端工具restclient-ui-2.3-jar-with-dependencies.jar可以再一下地址取下载

http://rest-client.googlecode.com/files/restclient-ui-2.3-jar-with-dependencies.jar

 

json格式化工具推荐用JSON Viewer

 

结果为:

 

{

    "isture": false,

    "list": [

        "data1",

        "data2"

    ],

    "map": {

        "key2": "keydata3",

        "key1": "keydata1"

    },

    "name": "张三",

    "num": 100,

    "operation": {

        "operationName": "用户登录",

        "operationType": "2",

        "operationURL": "/agent/login.action"

    }

}