2019独角兽企业重金招聘Python工程师标准>>>


测试struts.xml中result参数的不同返回不同的json数据

目的是为了比较result中type不同和result中参数的不同所产生的效果

如果查询的是所有的数据,在action中定义的类型如下:

private List<Goods> entities;
public List<Goods> getEntities() {
return entities;
}


1.第一种:
在xml文件中如果没有param,内容如下:
<action name="goods" class="cn.csdn.hr.action.GoodsAction">
<result type="json"/>
</action>


它得到的是json数据,但是autocomplete解析不出这样的json格式,所以读取不出来,结果为:
{"entities":[{"id":2,"name":"老王 ","price":222.0},{"id":1,"name":"老王 ","price":222.0},{"id":3,"name":"老王 ","price":222.0},{"id":4,"name":"老王 ","price":222.0},{"id":5,"name":"老王 ","price":222.0}]
.
2.第二种:如果加上param的name为多的那个对象,则可以返回的是json数据
<action name="goods" class="cn.csdn.hr.action.GoodsAction">
<result type="json">
<param name="root">entities</param>
</result>
</action>


返回的数据为:
[{"id":2,"name":"老王 ","price":222.0},{"id":1,"name":"老王 ","price":222.0},{"id":3,"name":"老王 ","price":222.0},{"id":4,"name":"老王 ","price":222.0},{"id":5,"name":"老王 ","price":222.0}]

可见返回的是json数据,并且在智能提示中可以提取出来,可以得知:
<param name="root">entities</param>
的意思是从根节点为entities的开始遍历,所有看到的数据就是json数据了。

3.如果在action中封装的是一个实体,也就是查询的是一条数据,则代码为:
private Goods entity;
public Goods getEntity() {
return entity;
}

响应的数据为:
{"entity":{"id":1,"name":"老王 2","price":222.0}}

4.如果加上param参数,则返回的是
<action name="goods" class="cn.csdn.hr.action.GoodsAction">
<result type="json">
<param name="root">entity</param>
</result>
</action>
结果为:{"id":1,"name":"老王 2","price":222.0}

5.如果在action中的数据为:
private List<Goods> entities;

private Goods entity;

public List<Goods> getEntities() {
return entities;
}

public Goods getEntity() {
return entity;
}

在xml文件中的数据为:
<action name="goods" class="cn.csdn.hr.action.GoodsAction">
<result type="json">
<param name="root">entity</param>
</result>
</action>


则返回的只是entity对应的实体
{"id":1,"name":"老王 2","price":222.0}


6.如果为:
<action name="goods" class="cn.csdn.hr.action.GoodsAction">
<result type="json">
<param name="root">entities</param>
</result>
</action>


则返回的只是entities的实体,为
[{"id":2,"name":"老王 ","price":222.0},{"id":1,"name":"老王 ","price":222.0},{"id":3,"name":"老王 ","price":222.0},{"id":4,"name":"老王 ","price":222.0},{"id":5,"name":"老王 ","price":222.0}]

7.如果在xml中的文件为:
<action name="goods" class="cn.csdn.hr.action.GoodsAction">
<result type="json">
<param name="root">entities,entity</param>
</result>
</action>

那么返回的数据为:
{"id":1,"name":"老王 2","price":222.0}

也就是谁在后面返回的是哪个

.8。如果xml数据为:
<result type="json">
<param name="includeProperties">entities</param>
</result>

返回的结果为:
{"entities":[]}

9.如果xml中数据为:
<result type="json">
<param name="includeProperties">entities\[\d+\].name</param>
</result>

返回的数据为:
{"entities":[{"name":"老王1 "},{"name":"老王 2"},{"name":"老王3 "},{"name":"老王4 "},{"name":"老王5 "}]}

10.如果xml中数据为:
<result type="json">
<param name="includeProperties">^entities\[\d+\].name</param>
</result>
返回的数据为:
{"entities":[{"name":"老王1 "},{"name":"老王 2"},{"name":"老王3 "},{"name":"老王4 "},{"name":"老王5 "}]}

这个是返回全部Action中getter方法的参数<param name="root">action</param>

还有就是官网的介绍,听详细的!

http://struts.apache.org/release/2.2.x/docs/json-plugin.html

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.

Given this JSON string:

{   "doubleValue": 10.10,   "nestedBean": {      "name": "Mr Bean"},   "list": ["A", 10, 20.20, {      "firstName": "El Zorro"}],   "array": [10, 20]
}

The action must have a "setDoubleValue" method, taking either a "float" or a "double" argument (the interceptor will convert the value to the right one). There must be a "setNestedBean" whose argument type can be any class, that has a "setName" method taking as argument an "String". There must be a "setList" method that takes a "List" as argument, that list will contain: "A" (String), 10 (Long), 20.20 (Double), Map ("firstName" -> "El Zorro"). The "setArray" method can take as parameter either a "List", or any numeric array.

So serialize your objects to JSON in javascript see json2

Installation

This plugin can be installed by copying the plugin jar into your application's /WEB-INF/lib directory. No other files need to be copied or created.

To use maven, add this to your pom:

<dependencies>...   <dependency><groupId>org.apache.struts</groupId><artifactId>struts2-json-plugin</artifactId><version>STRUTS_VERSION</version></dependency>...</dependencies>

Customizing Serialization and Deserialization

Use the JSON annotation to customize the serialization/deserialization process. Available JSON annotation fields:

Name Description Default Value Serialization Deserialization
name Customize field name empty yes no
serialize Include in serialization true yes no
deserialize Include in deserialization true no yes
format Format used to format/parse a Date field "yyyy-MM-dd'T'HH:mm:ss" yes yes

Excluding properties

A comma-delimited list of regular expressions can be passed to the JSON Result and Interceptor, properties matching any of these regular expressions will be ignored on the serialization process:

<!-- Result fragment --><result type="json"><param name="excludeProperties">login.password,studentList.*\.sin  </param></result><!-- Interceptor fragment --><interceptor-ref name="json"><param name="enableSMD">true</param><param name="excludeProperties">login.password,studentList.*\.sin  </param></interceptor-ref>

Including properties

A comma-delimited list of regular expressions can be passed to the JSON Result to restrict which properties will be serialized. ONLY properties matching any of these regular expressions will be included in the serialized output.

Note
Exclude property expressions take precedence over include property expressions. That is, if you use include and exclude property expressions on the same result, include property expressions will not be applied if an exclude exclude property expression matches a property first.
<!-- Result fragment --><result type="json"><param name="includeProperties">^entries\[\d+\]\.clientNumber,^entries\[\d+\]\.scheduleNumber,^entries\[\d+\]\.createUserId  </param></result>

Root Object

Use the "root" attribute(OGNL expression) to specify the root object to be serialized.

<result type="json"><param name="root">person.job  </param></result>

The "root" attribute(OGNL expression) can also be used on the interceptor to specify the object that must be populated, make sure this object is not null.

<interceptor-ref name="json"><param name="root">bean1.bean2</param></interceptor-ref>

Wrapping

For several reasons you might want to wrap the JSON output with some text, like wrapping with comments, adding a prefix, or to use file uploads which require the result to be wrapped in a textarea. Use wrapPrefix to add content in the beginning and wrapPostfix to add content at the end. This settings take precedence over "wrapWithComments" and "prefix" which are deprecated from 0.34 on. Examples:
Wrap with comments:

<result type="json"><param name="wrapPrefix">/*</param><param name="wrapSuffix">*/</param></result>

Add a prefix:

<result type="json"><param name="wrapPrefix">{}&&</param></result>

Wrap for file upload:

<result type="json"><param name="wrapPrefix"><![CDATA[<html><body><textarea>]]></param><param name="wrapSuffix"><![CDATA[</textarea></body></html>]]></param></result>

Wrap with Comments

wrapWithComments is deprecated from 0.34, use wrapPrefix and wrapSuffix instead.
wrapWithComments can turn safe JSON text into dangerous text. For example,

["*/ alert('XSS'); /*"]

Thanks to Douglas Crockford for the tip!. Consider using prefix instead.

If the serialized JSON is {name: 'El Zorro'}. Then the output will be: {}&& ({name: 'El Zorro'}

If the "wrapWithComments" (false by default) attribute is set to true, the generated JSON is wrapped with comments like:

/* {   "doubleVal": 10.10,   "nestedBean": {      "name": "Mr Bean"},   "list": ["A", 10, 20.20, {      "firstName": "El Zorro"}],   "array": [10, 20]
} */

To strip those comments use:

var responseObject = eval("("+data.substring(data.indexOf("\/\*")+2, data.lastIndexOf("\*\/"))+")");

Prefix

prefix is deprecated from 0.34, use wrapPrefix and wrapSuffix instead.

If the parameter prefix is set to true, the generated JSON will be prefixed with "{}&& ". This will help prevent hijacking. See this Dojo Ticket for details:

<result type="json"><param name="prefix">true</param></result>

Base Classes

By default properties defined on base classes of the "root" object won't be serialized, to serialize properties in all base classes (up to Object) set "ignoreHierarchy" to false in the JSON result:

<result type="json"><param name="ignoreHierarchy">false</param></result>

Enumerations

By default, an Enum is serialized as a name=value pair where value = name().

  public enum AnEnum {ValueA,ValueB}JSON:  "myEnum":"ValueA"

Use the "enumAsBean" result parameter to serialize Enum's as a bean with a special property _name with value name(). All properties of the enum are also serialized.

  public enum AnEnum {ValueA("A"),ValueB("B");     private String val;     public AnEnum(val) {        this.val = val;}     public getVal() {        return val;}}JSON:  myEnum: { "_name": "ValueA", "val": "A" }

Enable this parameter through struts.xml:

<result type="json"><param name="enumAsBean">true</param></result>

Compressing the output.

Set the enableGZIP attribute to true to gzip the generated json response. The request must include "gzip" in the "Accept-Encoding" header for this to work.

<result type="json"><param name="enableGZIP">true</param></result>

Preventing the browser from caching the response

Set noCache to true(false by default) to set the following headers in the response:

  • Cache-Control: no-cache

  • Expires: 0

  • Pragma: No-cache

<result type="json"><param name="noCache">true</param></result>

Excluding properties with null values

By default fields with null values are serialized like {property_name: null}. This can be prevented by setting excludeNullProperties to true.

<result type="json"><param name="excludeNullProperties">true</param></result>

Status and Error code

Use statusCode to set the status of the response:

<result type="json"><param name="statusCode">304</param></result>

And errorCode to send an error(the server might end up sending something to the client which is not the serialized JSON):

<result type="json"><param name="errorCode">404</param></result>

JSONP

To enable JSONP, set the parameter callbackParameter in either the JSON Result or the Interceptor. A parameter with that name will be read from the request, and it value will be used as the JSONP function. Assuming that a request is made with the parameter "callback"="exec":

<result type="json"><param name="callbackParameter">callback</param></result>

And that the serialized JSON is {name: 'El Zorro'}. Then the output will be: exec({name: 'El Zorro'})

Content Type

Content type will be set to application/json-rpc by default if SMD is being used, or application/json otherwise. Sometimes it is necessary to set the content type to something else, like when uploading files with Dojo and YUI. Use the contentType parameter in those cases.

<result type="json"><param name="contentType">text/html</param></result>

Example

Setup Action

This simple action has some fields:

Example:

import java.util.HashMap;import java.util.Map;import com.opensymphony.xwork2.Action;public class JSONExample {    private String field1 = "str";    private int[] ints = {10, 20};    private Map map = new HashMap();    private String customName = "custom";    //'transient' fields are not serialized    private transient String field2;    //fields without getter method are not serialized    private String field3;    public String execute() {map.put("John", "Galt");        return Action.SUCCESS;}    public String getField1() {        return field1;}    public void setField1(String field1) {        this.field1 = field1;}    public int[] getInts() {        return ints;}    public void setInts(int[] ints) {        this.ints = ints;}    public Map getMap() {        return map;}    public void setMap(Map map) {        this.map = map;}@JSON(name="newName")    public String getCustomName() {        return this.customName;}
}

Write the mapping for the action

  1. Add the map inside a package that extends "json-default"

  2. Add a result of type "json"

Example:

<?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="example"  extends="json-default"><action name="JSONExample" class="example.JSONExample"><result type="json"/></action></package></struts>

JSON example output

{  "field1" : "str", "ints": [10, 20],   "map": {       "John":"Galt"},   "newName": "custom"}

JSON RPC

The json plugin can be used to execute action methods from javascript and return the output. This feature was developed with Dojo in mind, so it uses Simple Method Definition to advertise the remote service. Let's work it out with an example(useless as most examples).

First write the action:

package smd;import com.googlecode.jsonplugin.annotations.SMDMethod;import com.opensymphony.xwork2.Action;public class SMDAction {    public String smd() {        return Action.SUCCESS;}@SMDMethod    public Bean doSomething(Bean bean, int quantity) {bean.setPrice(quantity * 10);        return bean;}
}

Methods that will be called remotely must be annotated with the SMDMethod annotation, for security reasons. The method will take a bean object, modify its price and return it. The action can be annotated with the SMD annotation to customize the generated SMD (more on that soon), and parameters can be annotated with SMDMethodParameter. As you can see, we have a "dummy", smdmethod. This method will be used to generate the Simple Method Definition (a definition of all the services provided by this class), using the "json" result.

The bean class:

package smd;public class Bean {    private String type;    private int price;    public String getType() {        return type;}    public void setType(String type) {        this.type = type;}    public int getPrice() {        return price;}    public void setPrice(int price) {        this.price = price;}}

The mapping:

<package name="RPC" namespace="/nodecorate" extends="json-default"><action name="SMDAction" class="smd.SMDAction" method="smd"><interceptor-ref name="json"><param name="enableSMD">true</param></interceptor-ref><result type="json"><param name="enableSMD">true</param></result></action></package>

Nothing special here, except that both the interceptor and the result must be applied to the action, and "enableSMD" must be enabled for both.

Now the javascript code:

<s:url id="smdUrl" namespace="/nodecorate" action="SMDAction" />
<script type="text/javascript">    //load dojo RPC    dojo.require("dojo.rpc.*");    //create service object(proxy) using SMD (generated by the json result)    var service = new dojo.rpc.JsonService("${smdUrl}");    //function called when remote method returns    var callback = function(bean) {alert("Price for " + bean.type + " is " + bean.price);};    //parameter    var bean = {type: "Mocca"};    //execute remote method    var defered = service.doSomething(bean, 5);    //attach callback to defered object    defered.addCallback(callback);
</script>

Dojo's JsonService will make a request to the action to load the SMD, which will return a JSON object with the definition of the available remote methods, using that information Dojo creates a "proxy" for those methods. Because of the asynchronous nature of the request, when the method is executed, a deferred object is returned, to which a callback function can be attached. The callback function will receive as a parameter the object returned from your action. That's it.

Proxied objects

As annotations are not inherited in Java, some user might experience problems while trying to serialize objects that are proxied. eg. when you have attached AOP interceptors to your action.

In this situation, the plugin will not detect the annotations on methods in your action.

To overcome this, set the "ignoreInterfaces" result parameter to false (true by default) to request that the plugin inspects all interfaces and superclasses of the action for annotations on the action's methods.

NOTE: This parameter should only be set to false if your action could be a proxy as there is a performance cost caused by recursion through the interfaces.

<action name="contact" class="package.ContactAction" method="smd"><interceptor-ref name="json"><param name="enableSMD">true</param><param name="ignoreSMDMethodInterfaces">false</param></interceptor-ref><result type="json"><param name="enableSMD">true</param><param name="ignoreInterfaces">false</param></result><interceptor-ref name="default"/>
</action>

转载于:https://my.oschina.net/lzwenme/blog/270275

Struts.xml配置返回JSON数据相关推荐

  1. 深入了解Struts2返回JSON数据的原理及具体应用范例

    来源:http://yshjava.iteye.com/blog/1333104 早在我刚学Struts2之初的时候,就想写一篇文章来阐述Struts2如何返回JSON数据的原理和具体应用了,但苦于一 ...

  2. (配置消息转换器)解决后台返回json数据到前台时页面时中文显示乱码问题

    (配置消息转换器)解决后台返回json数据到前台时页面时中文显示乱码问题 SpringMVC.xml中加 <!-- 配置消息转换器(解决中文乱码问题)--><mvc:annotati ...

  3. ajax处理返回的xml数据,使用AJAX调用WebService返回xml不返回json原因以及解决办法...

    初次尝试用AJAX调用webservice,结果无论怎么设置webservice返回的都是xml对象,一般的jquery处理json是更方便的. webservice理论上将下面这段代码按照说明取消注 ...

  4. 浅谈Struts2的命名空间及以传统形式返回json数据

    为什么80%的码农都做不了架构师?>>>    Struts2中在B/S传统应用中使用时需要配置struts.xml文件, 那么Struts2以传统形式 返回json 数据到客户端同 ...

  5. 从源代码角度看Struts2返回JSON数据的原理

    2019独角兽企业重金招聘Python工程师标准>>> 前面一篇文章其实只是介绍了如何在Struts2中返回JSON数据到客户端的具体范例而无关其原理,内容与标题不符惹来标题党嫌疑确 ...

  6. Struts2返回Json数据(使用Struts2插件)

    这篇我将介绍如何使用Struts2的struts2-json-plugin.jar插件返回JSON数据. 一.其中主要步骤有: 1.将struts2-json-plugin.jar插件拷贝到项目的&q ...

  7. ajax请求Struts2返回JSON数据方法

    如果是作为客户端的HTTP+JSON接口工程,没有JSP等view视图的情况下,使用Jersery框架开发绝对是第一选择.而在基于Spring3 MVC的架构下,对HTTP+JSON的返回类型也有很好 ...

  8. spring MVC之返回JSON数据(Spring3.0 MVC+Jackson+AJAX)

    参考: http://angelbill3.iteye.com/blog/1985075 问题:在进行springmvc返回json数据的时候报如下错误:用上面的controller,访问:http: ...

  9. Struts2里的Action返回Json数据

    hibernateTemplate和hibernateDaoSupport的注意问题! 正则表达式入门30分钟 Struts2里的Action返回Json数据 2010-08-03 22:46:46| ...

最新文章

  1. mysqlls_mysql基本命令
  2. 阿里开源新一代人机对话模型 ESIM,曾创下人机对话准确率新纪录
  3. 多比矢量图开发手册(六)-Web高级图元编程
  4. 【Python】Pandas profiling 生成报告并部署的一站式解决方案
  5. 强势崛起的Python会在十年内取代Java吗?
  6. .NET c# Color对象的使用介绍(转)
  7. 怎样正确使用和维护微型计算机,下篇:微型计算机应该怎样进行维护与保养
  8. linux下的redis配置;
  9. Vb.net/VB 声明API功能父窗口功能
  10. Android4.0升级新特性
  11. Tomcat startup.bat 后台运行,不再弹出 Dos 黑框
  12. sprint() 和 snprint()
  13. Github代码安全监控
  14. Spring 之 BeanFactory 源码 - 抽象/类 分析
  15. JMeter中BeanShell的使用方法和常用语法
  16. python blp模型 估计_简述BLP模型
  17. scandef格式详细说明
  18. 演讲实录:“分布式数据库海量数据存储和实时查询实现与应用”
  19. rimraf与windows的rmdir简单使用命令方法
  20. el-dialog修改弹框到顶部的高度margin-top

热门文章

  1. 又来?软件测试之接口自动化面试题汇总
  2. python量化常用_简单介绍下量化分析的常用库TA-lib
  3. mfc搜索新建access字段_vs2010MFC中使用ODBC链接ACCESS数据库,怎样编写查找功能?...
  4. arcgis栅格邻域统计_运用ArcGIS进行影像分类
  5. 二维标准正态分布的matlab方程
  6. 建立一个端口为8189的服务器,它无限期等待直到有客户连接这个端口。若客户在网上发送正确的请求连接了这个端口,则服务器与客户之间就建立了一个可靠的连接。
  7. git ssh配置完后拉取代码_二、windows下使用git拉取github上的项目(通过设置ssh key方式)...
  8. java jquery怎么取值_jquery 取值
  9. linux定时删除文件指令,Linux实践——定时删除目录下面的文件
  10. 脉冲编码调制pcm matlab,基于MATLAB的脉冲编码调制PCM