工具类Fn.java
package cn.edu.hziee.util;
import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
public class Fn {
public static void ajaxReturn(HttpServletResponse response,Object data,String info,String status){
Map<String, Object> jsonData = new HashMap<String, Object>();
jsonData.put("data", data);
jsonData.put("info", info);
jsonData.put("status", status);
render(response, JSON.toJSONString(jsonData), "json");
}
public static void render(HttpServletResponse response,
String text, String... contentType) {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
PrintWriter out = null;
try {
out = response.getWriter();
out.write(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
out.close();
}
}
}
controller中部分代码
/**
*测试其他JSON数据交互
*/
@RequestMapping("test")
public String test(HttpServletResponse response){
List<Student> data = new ArrayList<Student>();
Student stu1 = new Student("张三","123456");
Student stu2 = new Student("李欣","123456");
data.add(stu1);
data.add(stu2);
Fn.ajaxReturn(response, data, "成功", "1");
return null;
}
测试页面test.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div id="app"></div>
<script>
$.ajax({
type: "GET",
url: "${pageContext.request.contextPath }/test",
dataType: "JSON",
//采用jQuery的each方法对返回的集合数据进行遍历,这里结合html元素<div>在页面进行局部刷新操作
success: function(data){
alert("返回info:"+data.info+",返回status:"+data.status);
$.each(data.data,function(i,val){
$("#app").append(i+"---"+val.username+"---"+val.password+"<br>");
});
}
});
</script>
</body>
</html>