struts2配置JSON有两种方式,这里只介绍xml方式,注解请看下篇。配置json共分为二步:
(1)struts.xml
<span style="font-size:18px;"><!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="json" extends="struts-default,json-default" namespace="/">
<action name="testAction" class="com.oraclewdp.action.TestAction" method="doAction">
<result name="success" type="json">
<param name="includeProperties">msg</param>
</result>
</action>
</package>
</struts></span>
(2)testAction.java
<span style="font-size:18px;">package com.oraclewdp.action;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport implements Serializable{
private String msg;
public String doAction(){
msg="这是json数据";
return SUCCESS;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}</span>
上面是一个简单的例子,下面详细介绍一下struts.xml里面<param></param>
- root:只包含xx对象
- excludeProperties :除了xx之外的集合
- includeProperties : 包含xx的集合
- wrapPrefix :json结果开头添加xx(比如 [)
- wrapSuffix :同上,只不过是结尾
- ignoreHierarchy :转化时是否忽略继承关系true/false
- enumAsBean : 是否将枚举当做一个bean处理
- enableGZIP :是否支持gzip压缩输出
- noCache :是否缓存
- excludeNullProperties : 是否转化输出 null值
- statusCode :设置响应代号比如 304
- callbackParameter : JSONP跨域访问的回调设置
- contentType : 输出类型
注意事项:对于list,map数据在<param name="???"></param>中应该写成<param name="???">list.*,map.*</param>