servlet整合ajax接受和返回json数据
1.准备工作和前提条件
ide工具使用的是eclipse(自我感觉eclipse建普通的servlet的项目比idea简洁轻便)使用tomcat版本是7使用的servlet是2.5(建议使用这个版本,是xml配置版本)在lib包下引入lombok依赖,build path到项目中在lib包下引入jackson相关的依赖,java和json对象互转需要使用
jackson-annotations-2.4.0.jarjackson-core-2.4.2.jarjackson-databind-2.4.2.jar
2.测试的pojo类
package com
.shaoming
.pojo
;
import java
.util
.Date
;
import com
.fasterxml
.jackson
.annotation
.JsonFormat
;
import com
.fasterxml
.jackson
.annotation
.JsonProperty
;
import lombok
.AllArgsConstructor
;
import lombok
.Data
;
import lombok
.NoArgsConstructor
;
import lombok
.experimental
.Accessors
;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain
=true)
public class Employ {
@JsonProperty(value
= "empid")
private Integer id
;
@JsonProperty(value
= "empjob")
private String job
;
@JsonProperty(value
= "empname")
private String name
;
@JsonProperty(value
= "salary")
private Double salary
;
@JsonProperty(value
= "生日")
@JsonFormat(pattern
= "yyyyMMdd HHmmss",timezone
="GMT+8")
private Date birthday
;
private String strdate
;
}
说明:
@JsonFormat(pattern = “yyyyMMdd HHmmss”,timezone=“GMT+8”)
private Date birthday;
作用:格式化返回数据的时间格式
@JsonProperty(value = “empid”) private Integer id;
作用:指定返回数据id的名字是empid,不叫这个注解,返回的json数据id的名字就是id
3.java对象转json格式字符窜的工具类
使用的是jackson里面的ObjectMapper工具类
MyUtil.java
package com
.shaoming
.util
;
import org
.apache
.tomcat
.util
.http
.mapper
.Mapper
;
import com
.fasterxml
.jackson
.core
.JsonProcessingException
;
import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
public class MyUtils {
private static ObjectMapper mapper
= null
;
static {
mapper
= new ObjectMapper();
}
public static String
toJson(Object obj
) throws JsonProcessingException
{
String json
= mapper
.writeValueAsString(obj
);
return json
;
}
}
4.写servlet接受请求
servlet的模板
public class XxxServlet extends HttpServlet {
protected void doGet(HttpServletRequest request
, HttpServletResponse response
)
throws ServletException
, IOException
{
request
.setCharacterEncoding("utf-8");
response
.setContentType("text/html;charset=utf-8");
response
.setContentType("application/json");
}
protected void doPost(HttpServletRequest request
, HttpServletResponse response
)
throws ServletException
, IOException
{
doGet(request
, response
);
}
}
编写AjaxServlet模板
package com
.shaoming
.servlet
;
import java
.io
.BufferedReader
;
import java
.io
.IOException
;
import java
.io
.InputStreamReader
;
import java
.io
.PrintWriter
;
import java
.util
.Date
;
import javax
.servlet
.ServletException
;
import javax
.servlet
.ServletInputStream
;
import javax
.servlet
.http
.HttpServlet
;
import javax
.servlet
.http
.HttpServletRequest
;
import javax
.servlet
.http
.HttpServletResponse
;
import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
import com
.shaoming
.pojo
.Employ
;
import com
.shaoming
.util
.MyUtils
;
public class AjaxServlet extends HttpServlet {
private static final long serialVersionUID
= 1L
;
protected void doGet(HttpServletRequest request
, HttpServletResponse response
)
throws ServletException
, IOException
{
request
.setCharacterEncoding("utf-8");
response
.setContentType("text/html;charset=utf-8");
response
.setContentType("application/json");
Employ employ
= new Employ();
employ
.setBirthday(new Date()).setId(33333).setJob("工作").setName("姓名").setSalary(100.0).setStrdate("20202020");
String json
= MyUtils
.toJson(employ
);
System
.out
.println("json数据打印到控制台上,内容如下 \n");
System
.out
.println(json
);
PrintWriter out
= response
.getWriter();
out
.print(json
);
System
.out
.println("**************************");
BufferedReader reader
= new BufferedReader(new InputStreamReader(request
.getInputStream(), "utf-8"));
String temp
= null
;
String jsondata
= "";
while ((temp
= reader
.readLine()) != null
) {
jsondata
+= temp
;
}
reader
.close();
System
.out
.println(jsondata
);
ObjectMapper mapper
= new ObjectMapper();
Employ e
= mapper
.readValue(jsondata
, Employ
.class);
System
.out
.println(e
);
java
.lang
.String json2
= MyUtils
.toJson(e
);
System
.out
.println(json2
);
}
protected void doPost(HttpServletRequest request
, HttpServletResponse response
)
throws ServletException
, IOException
{
doGet(request
, response
);
}
}
说明:
这个是获取到发送过来的json格式的字符窜,用ObjectMapper类转成java对象,就可以在java里面使用了
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), “utf-8”)); String temp = null; String jsondata = “”; while ((temp = reader.readLine()) != null) { jsondata += temp; } reader.close(); System.out.println(jsondata);
编写ajax请求的jsp页面
index.jsp
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=utf8"
pageEncoding="utf8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<title>测试ajax和servlet之间的请求响应</title>
<!-- 引入jQuery -->
<script src="jquery-1.8.3.min.js"></script>
</head>
<body>
<button id="btn1">我是一个测试按钮</button>
<button id="btn2">我是一个测试跨域按钮</button>
<a href="http://localhost:8080/page_oracl/hello/totestajax">超链接测试跨域</a>
<script>
$("#btn1").click(function() {
funajax();
});
function funajax() {
alert("下面发送ajax请求");
//模拟一个json数据给servlet接受
var empObj = {
strdate : "20202020",
empid : 1000,
empjob : "工作",
empname : "姓名",
salary : 102.11,
生日 : "20200620 141635"
};
var empjson = {
"strdate" : "20202023",
"empid" : 222,
"empjob" : "工作",
"empname" : "姓名",
"salary" : 100.0,
"生日" : "20200620 140716"
};
//alert(typeof (empObj));//object类型
//alert(typeof (empjson));//object类型
//alert(typeof (JSON.stringify(empObj)));//string类型
//alert(typeof (JSON.stringify(empjson)));//string类型
$.ajax({
url : "http://localhost:8080/java-web/AjaxServlet",
//说明:无论时get和post,HttpServlet都是可以接受的
/**
如果传递json数据必须时post
*/
type : "post",
data : JSON.stringify(empjson),
contentType:"application/json;charset=utf-8",//发送给后台数据的格式
async : true,//表示异步请求
dataType : "json",
success : function(result) {
console.log(result);
},
error : function() {
alert("ajax请求失败");
}
});
}
</script>
</script>
</body>
</html>
说明:
js中js对象和json格式字符串之间的互相转换
1.js对象转json格式的字符窜
JSON.parse(str)
2.json格式的字符串转json对象
JSON.stringify(empjson)
js和json格式字符串互相转换的案例
F12后在chorm的console控制台上的测试案例
var emp
= {id
:18,name
:"name的值"}
undefined
var empjson
= JSON
.stringify(emp
);
undefined
console
.log(empjson
);
VM1831
:1 {"id":18,"name":"name的值"}
undefined
var empjsobj
= JSON
.parse(empjson
);
undefined
console
.log(empjsobj
);
VM2000
:1 {id
: 18, name
: "name的值"}
undefined