日期:2014-05-16  浏览次数:20520 次

Struts2返回JSON数据示例

1. 导包

??? 除导入Struts2基本包以外还要导入struts2-json-plugin-2.3.15.3.jar

?

2. 实现Action(JSONExample.java)

package test;
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.Action;
import org.apache.struts2.json.annotations.JSON;
public class JSONExample{
?? ?//模拟处理结果的属性
?? ?private int[] ints = {10, 20};
?? ?private Map<String , String> map = new HashMap<String , String>();
?? ?private String customName = "顾客";
?? ?//封装请求参数的三个属性
?? ?private String field1;
?? ?//'transient'修饰的属性不会被序列化
?? ?private transient String field2;
?? ?//没有setter和getter方法的字段不会被序列化
?? ?private String field3;
?? ?public String execute(){
?? ??? ?field2 = "333";
?? ??? ?map.put("name", "疯狂Java讲义");
?? ??? ?return Action.SUCCESS;
?? ?}
?? ?//使用注释语法来改变该属性序列化后的属性名
?? ?@JSON(name="newName")
?? ?public Map getMap(){
?? ??? ?return this.map;
?? ?}
?? ?//customName属性的setter和getter方法
?? ?public void setCustomName(String customName){
?? ??? ?this.customName = customName;
?? ?}
?? ?public String getCustomName(){
?? ??? ?return this.customName;
?? ?}
?? ?//field1属性的setter和getter方法
?? ?public void setField1(String field1){
?? ??? ?this.field1 = field1;
?? ?}
?? ?public String getField1(){
?? ??? ?return this.field1;
?? ?}
?? ?//field2属性的setter和getter方法
?? ?public void setField2(String field2){
?? ??? ?this.field2 = field2;
?? ?}
?? ?public String getField2(){
?? ??? ?return this.field2;
?? ?}
?? ?//field3属性的setter和getter方法
?? ?public void setField3(String field3){
?? ??? ?this.field3 = field3;
?? ?}
?? ?public String getField3(){
?? ??? ?return this.field3;
?? ?}
}

?

3. 配置Action(struts.xml)

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
?? ?"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
?? ?"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
?? ?<constant name="struts.i18n.encoding" value="UTF-8"/>
?? ?<package name="example"? extends="json-default">
?? ??? ?<action name="JSONExample" class="test.JSONExample">
?? ??? ??? ?<!-- 配置类型的json的Result -->
?? ??? ??? ?<result type="json">
?? ??? ??? ??? ?<!-- 为该Result指定参数 -->
?? ??? ??? ??? ?<param name="noCache">true</param>
?? ??? ??? ??? ?<param name="contentType">text/html</param>
?? ??? ??? ??? ?<!-- 设置只返回Action的map属性 -->
?? ??? ??? ??? ?<!--? param name="root">map</param -->
?? ??? ??? ?</result>
?? ??? ?</action>
?? ?</package>
</struts>

?

4. 测试返回结果

??? 浏览器输入: http://localhost:8080/TestStrutsJSON/example/JSONExample(项目路径+Action配置文件包名+Action名)