相关文章:
- 【JSON介绍】什么是JSON?
- 【Ajax】Ajax介绍
- 【Ajax】XMLHttpRequest介绍以及在前端如何实现Ajax
- 【Struts2】Sturts2如何实现JSON的数据输出,完成Ajax响应
Struts2 返回JSON数据有两种方式:
- 使用Servlet的输出流方式写入JSON字符串;
- 使用Struts2对JSON的扩展
1. 使用Servlet的输出流方式写入JSON字符串
JSON接口的实质是:JSON数据在传递过程中,其实就是传递一个普通的符合JSON语法格式的字符串而已,所谓的“JSON对象”是指对这个JSON字符串解析和包装后的结果。
直接上代码块:
/**
/*使用response对象获取PrintWriter对象从而将JSON对象输出
*/
//默认的HTTP报文中的响应类型为"text/html"
//设置响应类型为"application/json"
response.setContentType("application/json");
//使用PrintWriter对象的print方法将JSON对象输出,此处需要捕获IO异常
response.getWriter().print(jsonObject.toString());
2.使用Struts2对JSON的扩展
在Struts2框架的基础上还需要的jar包有:
- struts2-json-plugin-2.5.10.jar
- gson-2.8.0.jar 注:gson是Google公司开发,也可以使用json-lib或其他
也可以使用Maven依赖:
<!-- struts2-json-plugin -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>2.5.10.1</version>
</dependency>
<!-- Gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
- 完成action的java代码编写
为了突出struts2对于JSON的支持,代码块中省去了一些基本的流程
package com.baofeidyz.JqueryJsonAjaxStrust2Demo.web.action;
import com.google.gson.Gson;
public class UserAction{
//返回的json数据,变量名需要和后面在struts.xml文件中配置action时的变量名保持一致
String resultJSON = null;
public String registeredByAjax(){
//获取gson对象
Gson gson = new Gson();
//为了更好的表达struts2与JSON之间的关系,此处的messageJSON实际内容被简化
String messageJSON = "{"code":200}";
//使用gson对象的toJson方法序列化json对象,并转为字符串
resultJSON = gson.toJson(messageJSON).toString();
return "SUCCESS";
}
/**
* 必须要给返回的json数据添加set和get方法,不然struts2框架无法读取
*/
public String getResultJSON() {
return resultJSON;
}
public void setResultJSON(String resultJSON) {
this.resultJSON = resultJSON;
}
}
- 在struts.xml文件中注册action
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<!-- 需要继承json-default -->
<package name="baofeidyz" extends="struts-default,json-default">
<!-- 注册处理json的action -->
<action name="registeredByAjax"
class="com.baofeidyz.JqueryJsonAjaxStrust2Demo.web.action.UserAction"
method="registeredByAjax">
<!-- 较一般的action,需要在result中添加一个type属性,值填为json -->
<result name="SUCCESS" type="json">
<!-- 此处的resultJSON即在action中用于保存json的字符串变量,二者名字需要统一,且需要在action中添加变量的set和get方法 -->
<param name="root">resultJSON</param>
</result>
</action>
</package>
</struts>