浅谈struts2和json的集成

该例子以非常简单的形式描述了struts2和json的集成开发。。和大家共同学习。。
我用到的是struts2.2.3的jar包。
除了导入struts2的jar包外,还引入struts2-json-plugin.jar


[color=red]JSONExample.java[/color]

package com.lysf.json;

import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.json.annotations.JSON;

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;
}
}

[color=red]struts.xml[/color]

<package name="example" extends="json-default">
<action name="JSONExample" class="com.lysf.json.JSONExample">
<result type="json"/>
</action>
</package>

[color=red]web.xml[/color]

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


最后得到的结果为:

{"newName":"custom","field1":"str","ints":[10,20],"map":{"John":"Galt"}}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值