ajax是我们开发过程中常常用到,那么当ajax碰到struts2又会发生什么样的事情呢?通常笔者在使用ajax过程时更多是从服务端返回json格式的数据。下面就说说如何通过struts2来返回json数据。
首先来看一下我的struts2配置文件中action的配置
<package name="account" extends="struts-default" namespace="/account">
<action name="add" method="addAccount"
class="org.lian.account.actions.AccountAction" >
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
</package>
接下来是Action,Java类设计
public class AccountAction extends ActionSupport {
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public String addAccount() throws IOException {
Map<String, String> map = new HashMap<String, String>();
map.put("flag", "添加成功");
String result = GsonUtil.getInstance().convertToJson(map);
inputStream = new ByteArrayInputStream(result.getBytes("UTF-8"));
return SUCCESS;
}
}
Java对象和json字符串相互转换,使用google的gson工具包,使用的版本是2.8.0,下面是我工具类的代码
import com.google.gson.Gson;
public class GsonUtil {
private static GsonUtil util;
private GsonUtil() {
}
public static GsonUtil getInstance() {
if (util == null)
util = new GsonUtil();
return util;
}
/**
*
* @description TODO
* @param obj
* @return
* @return String
*/
public String convertToJson(Object obj) {
Gson gson = new Gson();
return gson.toJson(obj);
}
/**
*
* @description TODO
* @param json
* @param type
* @return
* @return T
*/
public <T> T parseJson(String json, Class<T> type) {
Gson gson = new Gson();
return gson.fromJson(json, type);
}
}
笔者已经将gson工具包上传了,如需要可以自行下载。