• struts2注解返回json


     

    Struts2使用注解方式返回Json数据

    最近项目中需要使用struts2的注解方式实现Json数据的返回 

    讲道理,网上一大堆解决方案,试了半天没有一个完全解决我的问题,因此集百家之长写了这篇博客,希望对大家有用。

     
     

    1.引入struts2-json-plugin和struts2-convention-plugin的jar包

    <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-json-plugin</artifactId>
            <version>${struts2.version}</version>
    </dependency>
    <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-convention-plugin</artifactId>
            <version>${struts2.version}</version>
    </dependency>

    2.Action类注解

    1.使用注解@ParentPackage("json-default")注解Action类

    2.设置result的type为json

    @Result(name = "error", type = "json")

    3 @JSON注解

    a.默认情况下以get方法会被序列化,

    b.可使用注解 @JSON(serialize=false)关闭某个get方法的序列化。

    c.如果在属性get方法上面加 @JSON(name=”newName”),则返回的json数据中key是指定的新名称。

    d. @JSON(format ="yyyy-MM-dd'T'HH:mm:ss”)设置用于格式化json数据中的日期。

    e. @JSON(deserialize=true)设置是否反序列化该属性。

    4.param参数设置

    4.1.root参数:返回单个数据

    使用方法::

    @Action(value="xxxx",results={ @Result(name=“xxx”type="json",params={"root","要返回的数据名称"})})

    4.2. excludeNullProperties 参数:过滤属性值为null的数据

    使用方法:: @Action(value="xxxx",results={ @Result(name=“xxx”type="json",params={“excludeNullProperties","true"})})

    4.3. ignoreHierarchy 参数:表示是否忽略等级。ignoreHierarchy值默认为true,设置为false后会将父类和子类的属性一起输出。

    使用方法:: @Action(value="xxxx",results={ @Result(name=“xxx”type="json",params={"ignoreHierarchy","true"})})

    4.4. includeProperties 参数:输出结果中需要包含的属性值,这里正则表达式和属性名匹配,可以用“,”分割多个正则表达式。

    使用方法:: @Action(value="xxxx",results={ @Result(name=“xxx”type="json",params={"includeProperties","msg,user\.username,list\[1\]\.password,map.*","prefix","true"})})

     

    4.5. excludeProperties 参数:输出结果需要排除的属性值,用法与includeProperties相同。

    使用方法:@Action(value="xxxx",results={ @Result(name=“xxx”type="json",

    params={"excludeProperties","msg,user\.username,list\[1\]\.password,map.*","prefix","true")})

     
     
  • 相关阅读:
    Win32K里的死循环
    Oracle 经常使用命令小结
    ImageView 会盖掉ScrollView的OnTouchListener,监听Activity的手势
    怎样安装pip--python的包管理工具
    设计模式-模板方法
    django中怎样生成非HTML格式的内容。
    SharePoint 2013 设置自己定义布局页
    Android读写JSON格式的数据之JsonWriter和JsonReader
    基于Linux 3.0.8 Samsung FIMC(S5PV210) 的摄像头驱动框架解读(一)
    BZOJ-1923-外星千足虫-SDOI2010
  • 原文地址:https://www.cnblogs.com/zxwBj/p/8670139.html
Copyright © 2020-2023  润新知