<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Templatetitle>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
head>
<body>
<h1>你好,世界!h1>
<button type="button" class="btn btn-info" onclick="tongbuSend()">同步请求button>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js">script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous">script>
<script>
function tongbuSend() {
$.ajax({
url: 'http://localhost:8080/Ahut/demo/getJson.action',
data: { name: "value" },
cache: false,
//async: false,
type: "POST",
dataType: 'jsonp',
jsonp: "jsonpCallback",
//其中success_jsonpCallback为自定义名称,与后台保持一致即可
jsonpCallback: "success_jsonpCallback",
success: function (result) {
alert(result.returnMethodName + ":" + result.returnType + ":" + result.returnValue)
}
});
}
script>
body>
html>
package com.ahut.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ahut.common.ReturnObject;
import com.ahut.utils.JsonUtil;
/**
*
* @ClassName: DemoAction
* @Description: 测试SpringMvc转json
* @author cheng
* @date 2017年6月17日 下午10:05:23
*/
@Controller
@RequestMapping(value = "/demo")
public class DemoAction {
/**
*
* @throws IOException
* @Title: getJson
* @Description:获取json测试
*/
@RequestMapping(value = "/getJson.action")
public void getJson(HttpServletRequest request,HttpServletResponse response) throws IOException {
ReturnObject returnObj = new ReturnObject();
returnObj.setSuccessMessage("yes,I get it!", "getJson");
PrintWriter pw = response.getWriter();
//success_jsonpCallback与前台保持一致
pw.write("success_jsonpCallback"+"("+JsonUtil.beanToJson(returnObj)+")");
pw.close();
pw = null;
}
}
输出json格式如下:
success_jsonpCallback({"returnMethodName":"getJson","returnType":"SUCCESS","returnValue":"yes,I get it!"})
package com.ahut.common;
/**
*
* @ClassName: ReturnObject
* @Description: 控制层返回
* @author cheng
* @date 2017年6月15日 下午11:15:35
*/
public class ReturnObject {
private String returnType;
private Object returnValue;
private String returnMethodName;
/**
* 取得返回结果 成功:success 失败:error
*
* @return String
*/
public String getReturnType() {
return returnType;
}
/**
* 设置返回结果 成功:success 失败:error
*
* @param returnType
*/
public void setReturnType(String returnType) {
this.returnType = returnType;
}
/**
* 取得返回值 如果success则是返回值;如果error则是错误信息
*
* @return Object
*/
public Object getReturnValue() {
return returnValue;
}
/**
* 设置返回值 如果success则是返回值;如果error则是错误信息
*
* @param returnValue
*/
public void setReturnValue(Object returnValue) {
this.returnValue = returnValue;
}
/**
* 取得执行的方法
*
* @return String
*/
public String getReturnMethodName() {
return returnMethodName;
}
/**
* 设置执行的方法
*
* @param returnMethodName
*/
public void setReturnMethodName(String returnMethodName) {
this.returnMethodName = returnMethodName;
}
/**
* 返回失败信息
*
* @param returnValue
* @param returnMethod
* @author chenchangfa
*/
public void setErrorMessage(Object returnValue, String returnMethod) {
this.setReturnType("ERROR");
this.setReturnValue(returnValue);
this.setReturnMethodName(returnMethod);
}
/**
* 返回成功信息
*
* @param returnValue
* @param returnMethod】
* @author chenchangfa
*/
public void setSuccessMessage(Object returnValue, String returnMethod) {
this.setReturnType("SUCCESS");
this.setReturnValue(returnValue);
this.setReturnMethodName(returnMethod);
}
}
package com.ahut.utils;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
*
* @ClassName: JsonUtil
* @Description: 处理json的工具类
* @author cheng
* @date 2017-3-27 下午4:41:30
*/
public final class JsonUtil {
/**
*
* @Title: jsonToBean
* @Description: json转javabean
* @param json
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public static final T jsonToBean(JSONObject json, Class clazz) {
return (T) JSONObject.toBean(json, clazz);
}
/**
*
* @Title: jsonToMap
* @Description: json转Map
* @param json
* @return
*/
@SuppressWarnings("unchecked")
public static final Map jsonToMap(JSONObject json) {
return json;
}
/**
*
* @Title: jsonToList
* @Description: json转list
* @param jsonArray
* @param t
* @return
*/
@SuppressWarnings({ "deprecation", "unchecked" })
public static final List jsonToList(JSONArray jsonArray, Class clazz) {
return JSONArray.toList(jsonArray, clazz);
}
/**
*
* @Title: jsonToArray
* @Description: json转array
* @param jsonArray
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public static final T[] jsonToArray(JSONArray jsonArray, Class clazz) {
return (T[]) JSONArray.toArray(jsonArray, clazz);
}
/**
*
* @Title: jsonToString
* @Description: json转String
* @param json
* @return
*/
public static final String jsonToString(JSONObject json) {
return json.toString();
}
/**
*
* @Title: beanToJson
* @Description: bean转json
* @param bean
* @return
*/
public static final JSONObject beanToJson(Object bean) {
return JSONObject.fromObject(bean);
}
/**
*
* @Title: mapToJson
* @Description: map转json
* @param map
* @return
*/
public static final JSONObject mapToJson(Map map) {
return JSONObject.fromObject(map);
}
/**
*
* @Title: listToJson
* @Description: list转json
* @param list
* @return
*/
public static final JSONArray listToJson(List list) {
return JSONArray.fromObject(list);
}
/**
*
* @Title: arrayToJson
* @Description: array转json
* @param array
* @return
*/
public static final JSONArray arrayToJson(Object[] array) {
return JSONArray.fromObject(array);
}
/**
*
* @Title: stringToJson
* @Description: String转json
* @param str
* @return
*/
public static final JSONObject stringToJson(String str) {
return JSONObject.fromObject(str);
}
}
其中使用jquery请求json代码如下:
$.ajax({
url: 'http://localhost:8080/Ahut/demo/getJson.action',
data: { name: "value" },
cache: false,
//async: false,
type: "POST",
dataType: 'jsonp',
jsonp: "jsonpCallback",
jsonpCallback: "success_jsonpCallback",
success: function (result) {
alert(result.returnMethodName + ":" + result.returnType + ":" + result.returnValue)
}
});
1.当其中dataType: ‘json’时,F12调试报如下错误:
XMLHttpRequest cannot load http://localhost:8080/Ahut/demo/getJson.action.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
2.修改dataType: ‘jsonp’后,若没有jsonp: “jsonpCallback”,jsonpCallback: “success_jsonpCallback”,F12调试报如下错误:
Uncaught ReferenceError: success_jsonpCallback is not defined
at getJson.action?callback=jQuery1124009…_1501597289726&name=value&_=1501597289727:1
3.若jquery请求如下
$.ajax({
url: 'http://localhost:8080/Ahut/demo/getJson.action',
data: { name: "value" },
cache: false,
type: "POST",
dataType: 'jsonp',
success: function (result) {
alert(result.returnMethodName + ":" + result.returnType + ":" + result.returnValue)
}
});
后台如下:
package com.ahut.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ahut.common.ReturnObject;
import com.ahut.utils.JsonUtil;
/**
*
* @ClassName: DemoAction
* @Description: 测试SpringMvc转json
* @author cheng
* @date 2017年6月17日 下午10:05:23
*/
@Controller
@RequestMapping(value = "/demo")
public class DemoAction {
/**
*
* @throws IOException
* @Title: getJson
* @Description:获取json测试
*/
@RequestMapping(value = "/getJson.action")
public void getJson(HttpServletRequest request,HttpServletResponse response) throws IOException {
ReturnObject returnObj = new ReturnObject();
returnObj.setSuccessMessage("yes,I get it!", "getJson");
PrintWriter pw = response.getWriter();
pw.write(JsonUtil.beanToJson(returnObj).toString());
pw.close();
pw = null;
}
}
返回的json格式如下:
{"returnMethodName":"getJson","returnType":"SUCCESS","returnValue":"yes,I get it!"}
此时,F12调试报如下错:
Uncaught SyntaxError: Unexpected token :
getJson.action?callback=jQuery1124004…_1501597026504&name=value&_=1501597026505:1