Java Web 15_AJAX&JSON
AJAX:
1. 概念: ASynchronous JavaScript And XML 异步的JavaScript 和 XML
1. 异步和同步:客户端和服务器端相互通信的基础上
* 客户端必须等待服务器端的响应。在等待的期间客户端不能做其他操作。
* 客户端不需要等待服务器端的响应。在服务器处理请求的过程中,客户端可以进行其他的操作。
Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。 [1]
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 Ajax)如果需要更新内容,必须重载整个网页页面。
提升用户的体验
2. 实现方式:
1. 原生的JS实现方式(了解)
//1.创建核心对象
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//2. 建立连接
/*
参数:
1. 请求方式:GET、POST
* get方式,请求参数在URL后边拼接。send方法为空参
* post方式,请求参数在send方法中定义
2. 请求的URL:
3. 同步或异步请求:true(异步)或 false(同步)
*/
xmlhttp.open("GET","ajaxServlet?username=tom",true);
//3.发送请求
xmlhttp.send();
//4.接受并处理来自服务器的响应结果
//获取方式 :xmlhttp.responseText
//什么时候获取?当服务器响应成功后再获取
//当xmlhttp对象的就绪状态改变时,触发事件onreadystatechange。
xmlhttp.onreadystatechange=function()
{
//判断readyState就绪状态是否为4,判断status响应状态码是否为200
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//获取服务器的响应结果
var responseText = xmlhttp.responseText;
alert(responseText);
}
}
2. JQeury实现方式
1. $.ajax()
* 语法:$.ajax({键值对});
//使用$.ajax()发送异步请求
$.ajax({
url:"ajaxServlet1111" , // 请求路径
type:"POST" , //请求方式
//data: "username=jack&age=23",//请求参数
data:{"username":"jack","age":23},
success:function (data) {
alert(data);
},//响应成功后的回调函数
error:function () {
alert("出错啦...")
},//表示如果请求响应出现错误,会执行的回调函数
dataType:"text"//设置接受到的响应数据的格式
});
2. $.get():发送get请求
* 语法:$.get(url, [data], [callback], [type])
* 参数:
* url:请求路径
* data:请求参数
* callback:回调函数
* type:响应结果的类型
3. $.post():发送post请求
* 语法:$.post(url, [data], [callback], [type])
* 参数:
* url:请求路径
* data:请求参数
* callback:回调函数
* type:响应结果的类型
JSON:
1. 概念: JavaScript Object Notation JavaScript对象表示法
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
var p = {"name":"张三","age":23,"gender":"男"};
* json现在多用于存储和交换文本信息的语法
* 进行数据的传输
* JSON 比 XML 更小、更快,更易解析。
2. 语法:
1. 基本规则
* 数据在名称/值对中:json数据是由键值对构成的
* 键用引号(单双都行)引起来,也可以不使用引号
* 值得取值类型:
1. 数字(整数或浮点数)
2. 字符串(在双引号中)
3. 逻辑值(true 或 false)
4. 数组(在方括号中) {"persons":[{},{}]}
5. 对象(在花括号中) {"address":{"province":"陕西"....}}
6. null
* 数据由逗号分隔:多个键值对由逗号分隔
* 花括号保存对象:使用{}定义json 格式
* 方括号保存数组:[]
2. 获取数据:
1. json对象.键名
2. json对象["键名"]
3. 数组对象[索引]
4. 遍历
//1.定义基本格式
var person = {"name": "张三", age: 23, 'gender': true};
var ps = [{"name": "张三", "age": 23, "gender": true},
{"name": "李四", "age": 24, "gender": true},
{"name": "王五", "age": 25, "gender": false}];
//获取person对象中所有的键和值
//for in 循环
/* for(var key in person){
//这样的方式获取不行。因为相当于 person."name"
//alert(key + ":" + person.key);
alert(key+":"+person[key]);
}*/
//获取ps中的所有值
for (var i = 0; i < ps.length; i++) {
var p = ps[i];
for(var key in p){
alert(key+":"+p[key]);
}
}
3. JSON数据和Java对象的相互转换
* JSON解析器:
* 常见的解析器:Jsonlib,Gson,fastjson,jackson
1. JSON转为Java对象
1. 导入jackson的相关jar包
2. 创建Jackson核心对象 ObjectMapper
3. 调用ObjectMapper的相关方法进行转换
1. readValue(json字符串数据,Class)
2. Java对象转换JSON
1. 使用步骤:
1. 导入jackson的相关jar包
2. 创建Jackson核心对象 ObjectMapper
3. 调用ObjectMapper的相关方法进行转换
1. 转换方法:
* writeValue(参数1,obj):
参数1:
File:将obj对象转换为JSON字符串,并保存到指定的文件中
Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
* writeValueAsString(obj):将对象转为json字符串
2. 注解:
1. @JsonIgnore:排除属性。
2. @JsonFormat:属性值得格式化
* @JsonFormat(pattern = "yyyy-MM-dd")
3. 复杂java对象转换
1. List:数组
2. Map:对象格式一致
案例:(异步用户名查重验证)
* 校验用户名是否存在
1. 服务器响应的数据,在客户端使用时,要想当做json数据格式使用。有两种解决方案:
1. $.get(type):将最后一个参数type指定为"json"
2. 在服务器端设置MIME类型
response.setContentType("application/json;charset=utf-8");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
//在页面加载完成后
$(function () {
//给username绑定blur事件
$("#username").blur(function () {
//获取username文本输入框的值
var username = $(this).val();
//发送ajax请求
//期望服务器响应回的数据格式:{"userExsit":true,"msg":"此用户名太受欢迎,请更换一个"}
// {"userExsit":false,"msg":"用户名可用"}
$.get("findUserServlet",{username:username},function (data) {
//判断userExsit键的值是否是true
// alert(data);
var span = $("#s_username");
if(data.userExsit){
//用户名存在
span.css("color","red");
span.html(data.msg);
}else{
//用户名不存在
span.css("color","green");
span.html(data.msg);
}
});
});
});
</script>
</head>
<body>
<form>
<input type="text" id="username" name="username" placeholder="请输入用户名">
<span id="s_username"></span>
<br>
<input type="password" name="password" placeholder="请输入密码"><br>
<input type="submit" value="注册"><br>
</form>
</body>
</html>
------------------------------------------------
------------------------------------------------
package cn.itcast.web.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取用户名
String username = request.getParameter("username");
//2.调用service层判断用户名是否存在
//期望服务器响应回的数据格式:{"userExsit":true,"msg":"此用户名太受欢迎,请更换一个"}
// {"userExsit":false,"msg":"用户名可用"}
//设置响应的数据格式为json
response.setContentType("application/json;charset=utf-8");
Map<String,Object> map = new HashMap<String,Object>();
if("tom".equals(username)){
//存在
map.put("userExsit",true);
map.put("msg","此用户名太受欢迎,请更换一个");
}else{
//不存在
map.put("userExsit",false);
map.put("msg","用户名可用");
}
//将map转为json,并且传递给客户端
//将map转为json
ObjectMapper mapper = new ObjectMapper();
//并且传递给客户端
mapper.writeValue(response.getWriter(),map);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
数据转换json
public JSONArray queryData2(String sql,SQLParameter ss) {
BaseDAO bs = new BaseDAO();
JSONArray resList = new JSONArray();
List<Map<String, Object>> bList = null ;
try {
if(ss==null){
bList = (List<Map<String, Object>>) bs.executeQuery(sql,new MapListProcessor());
}else{
bList = (List<Map<String, Object>>) bs.executeQuery(sql,ss,new MapListProcessor());
//[{item_displayname=人员编码, showorder=1, slip_item=code},
//{item_displayname=姓名, showorder=2, slip_item=name},
//{item_displayname=年度, showorder=3, slip_item=cyear},
//{item_displayname=期间, showorder=4, slip_item=cperiod},
//{item_displayname=基础工资实发, showorder=5, slip_item=f_170},
//{item_displayname=扣工会会费, showorder=6, slip_item=f_61},
//{item_displayname=学历工资, showorder=7, slip_item=f_79},
//{item_displayname=职称工资, showorder=8, slip_item=f_80},
//{item_displayname=加班工资, showorder=9, slip_item=f_81},
//{item_displayname=清凉饮料费, showorder=10, slip_item=f_25},
//{item_displayname=外出补助, showorder=11, slip_item=f_26},
//{item_displayname=烤火费, showorder=12, slip_item=f_27},
//{item_displayname=公积金, showorder=13, slip_item=f_31},
//{item_displayname=医疗保险, showorder=14, slip_item=f_32},
//{item_displayname=养老保险, showorder=15, slip_item=f_33},
//{item_displayname=失业保险, showorder=16, slip_item=f_83},
//{item_displayname=保险差额, showorder=17, slip_item=f_141},
//{item_displayname=公积金(单位), showorder=18, slip_item=f_131},
//{item_displayname=医疗保险(单位), showorder=19, slip_item=f_132},
//{item_displayname=养老保险(单位), showorder=20, slip_item=f_133},
// {item_displayname=失业保险(单位), showorder=21, slip_item=f_136},
//{item_displayname=工伤保险(单位), showorder=22, slip_item=f_138},
// {item_displayname=税费, showorder=23, slip_item=f_144},
//{item_displayname=应发工资, showorder=24, slip_item=f_44},
//{item_displayname=扣款合计., showorder=25, slip_item=f_45}]
}
// ObjectMapper o = new ObjectMapper();
for (int i = 0; i < bList.size(); i++) {
Map<String, Object> map = bList.get(i);
JSONObject agg = new JSONObject();
for(Entry<String, Object> a:map.entrySet()){
agg.put(a.getKey(), a.getValue() == null ? "" : a.getValue());
}
resList.add(agg);
}
} catch (BusinessException e) {
ErmBXLogger.getInstance().error("Tools=>queryData2:"+e.getMessage());
ExceptionUtils.wrappException(e);
}
return resList;
}
/*
{
"code": "100",
"msg": "操作成功!",
"data": [{
"key": {
"yearmonth": "201911"
},
"value": [{
"item_displayname": "税费",
"showorder": 23,
"slip_item": "f_144",
"value": 1673.44
}, {
"item_displayname": "学历工资",
"showorder": 7,
"slip_item": "f_79",
"value": 0
}, {
"item_displayname": "加班工资",
"showorder": 9,
"slip_item": "f_81",
"value": 0
}, {
"item_displayname": "外出补助",
"showorder": 11,
"slip_item": "f_26",
"value": 0
}, {
"item_displayname": "公积金(单位)",
"showorder": 18,
"slip_item": "f_131",
"value": 1628
}, {
"item_displayname": "姓名",
"showorder": 2,
"slip_item": "name",
"value": "贾晋伟"
}, {
"item_displayname": "保险差额",
"showorder": 17,
"slip_item": "f_141",
"value": 0
}, {
"item_displayname": "医疗保险(单位)",
"showorder": 19,
"slip_item": "f_132",
"value": 937.27
}, {
"item_displayname": "应发工资",
"showorder": 24,
"slip_item": "f_44",
"value": 5855.5
}, {
"item_displayname": "清凉饮料费",
"showorder": 10,
"slip_item": "f_25",
"value": 0
}, {
"item_displayname": "公积金",
"showorder": 13,
"slip_item": "f_31",
"value": 1628
}, {
"item_displayname": "养老保险(单位)",
"showorder": 20,
"slip_item": "f_133",
"value": 1499.68
}, {
"item_displayname": "失业保险(单位)",
"showorder": 21,
"slip_item": "f_136",
"value": 46.87
}, {
"item_displayname": "年度",
"showorder": 3,
"slip_item": "cyear",
"value": "2019"
}, {
"item_displayname": "医疗保险",
"showorder": 14,
"slip_item": "f_32",
"value": 192.46
}, {
"item_displayname": "人员编码",
"showorder": 1,
"slip_item": "code",
"value": "2225"
}, {
"item_displayname": "职称工资",
"showorder": 8,
"slip_item": "f_80",
"value": 0
}, {
"item_displayname": "烤火费",
"showorder": 12,
"slip_item": "f_27",
"value": 0
}, {
"item_displayname": "工伤保险(单位)",
"showorder": 22,
"slip_item": "f_138",
"value": 56.24
}, {
"item_displayname": "期间",
"showorder": 4,
"slip_item": "cperiod",
"value": "11"
}, {
"item_displayname": "基础工资实发",
"showorder": 5,
"slip_item": "f_170",
"value": 5855.5
}, {
"item_displayname": "扣工会会费",
"showorder": 6,
"slip_item": "f_61",
"value": 29.28
}, {
"item_displayname": "养老保险",
"showorder": 15,
"slip_item": "f_33",
"value": 749.84
}, {
"item_displayname": "失业保险",
"showorder": 16,
"slip_item": "f_83",
"value": 46.87
}, {
"item_displayname": "扣款合计.",
"showorder": 25,
"slip_item": "f_45",
"value": 4319.89
}]
}, {
"key": {
"yearmonth": "201912"
},
"value": [{
"item_displayname": "税费",
"showorder": 23,
"slip_item": "f_144",
"value": 1673.44
}, {
"item_displayname": "学历工资",
"showorder": 7,
"slip_item": "f_79",
"value": 0
}, {
"item_displayname": "加班工资",
"showorder": 9,
"slip_item": "f_81",
"value": 0
}, {
"item_displayname": "外出补助",
"showorder": 11,
"slip_item": "f_26",
"value": 0
}, {
"item_displayname": "公积金(单位)",
"showorder": 18,
"slip_item": "f_131",
"value": 1628
}, {
"item_displayname": "姓名",
"showorder": 2,
"slip_item": "name",
"value": "贾晋伟"
}, {
"item_displayname": "保险差额",
"showorder": 17,
"slip_item": "f_141",
"value": 0
}, {
"item_displayname": "医疗保险(单位)",
"showorder": 19,
"slip_item": "f_132",
"value": 937.27
}, {
"item_displayname": "应发工资",
"showorder": 24,
"slip_item": "f_44",
"value": 5855.5
}, {
"item_displayname": "清凉饮料费",
"showorder": 10,
"slip_item": "f_25",
"value": 0
}, {
"item_displayname": "公积金",
"showorder": 13,
"slip_item": "f_31",
"value": 1628
}, {
"item_displayname": "养老保险(单位)",
"showorder": 20,
"slip_item": "f_133",
"value": 1499.68
}, {
"item_displayname": "失业保险(单位)",
"showorder": 21,
"slip_item": "f_136",
"value": 46.87
}, {
"item_displayname": "年度",
"showorder": 3,
"slip_item": "cyear",
"value": "2019"
}, {
"item_displayname": "医疗保险",
"showorder": 14,
"slip_item": "f_32",
"value": 192.46
}, {
"item_displayname": "人员编码",
"showorder": 1,
"slip_item": "code",
"value": "2225"
}, {
"item_displayname": "职称工资",
"showorder": 8,
"slip_item": "f_80",
"value": 0
}, {
"item_displayname": "烤火费",
"showorder": 12,
"slip_item": "f_27",
"value": 0
}, {
"item_displayname": "工伤保险(单位)",
"showorder": 22,
"slip_item": "f_138",
"value": 56.24
}, {
"item_displayname": "期间",
"showorder": 4,
"slip_item": "cperiod",
"value": "12"
}, {
"item_displayname": "基础工资实发",
"showorder": 5,
"slip_item": "f_170",
"value": 5855.5
}, {
"item_displayname": "扣工会会费",
"showorder": 6,
"slip_item": "f_61",
"value": 0
}, {
"item_displayname": "养老保险",
"showorder": 15,
"slip_item": "f_33",
"value": 749.84
}, {
"item_displayname": "失业保险",
"showorder": 16,
"slip_item": "f_83",
"value": 46.87
}, {
"item_displayname": "扣款合计.",
"showorder": 25,
"slip_item": "f_45",
"value": 4290.61
}]
}, {
"key": {
"yearmonth": "202001"
},
"value": []
}]
}
*/
public JSONArray queryData_xinzi(String sql,SQLParameter ss) {
/*BaseDAO bs = new BaseDAO();
JSONArray all = new JSONArray();
List<Map<String, Object>> bList = null ;
bList = this.queryData2(sql, ss);
System.out.println(bList);
for (int i = 0; i < bList.size(); i++) {
Map<String, Object> map = bList.get(i);//第N条数据
//1、获取当前数据是否在编
List<Map<String, Object>> Listshow = null;
String bianzi = (String)map.get("bianzhi");
if("正编".equals(bianzi)){
}else{
}
}*/
/*BaseDAO bs = new BaseDAO();
JSONArray all = new JSONArray();
List<Map<String, Object>> bList = null ;
try {
if(ss==null){
bList = (List<Map<String, Object>>) bs.executeQuery(sql,new MapListProcessor());
}else{
bList = (List<Map<String, Object>>) bs.executeQuery(sql,ss,new MapListProcessor());
}
for (int i = 0; i < bList.size(); i++) {
Map<String, Object> map = bList.get(i);//第N条数据
//1、获取当前数据是否在编
List<Map<String, Object>> Listshow = null;
String bianzi = (String)map.get("bianzhi");
JSONObject queryData3 =new JSONObject();
if("正编".equals(bianzi)){
SQLParameter ss1 = new SQLParameter();
StringBuilder sql1 = new StringBuilder();
ss1.clearParams();
sql1.setLength(0);
sql1.append(" SELECT distinct wa.slip_item,wa.item_displayname,wa.showorder FROM wa_payslip_item wa WHERE wa.pk_payslip = '1001ZZ100000000MVC1M' \n");
JSONArray queryData2 = this.queryData2(sql1.toString(),ss1);
JSONObject tt =null;
for (int j = 0; j < queryData2.size(); j++) {
tt = queryData2.getJSONObject(j);
//tt.put(tt.get("slip_item").toString(), map.get(tt.get("slip_item").toString()));
tt.put("value", map.get(tt.get("slip_item").toString()));
// tt.put( tt.get("slip_item").toString(), map.get(tt.get("item_displayname").toString()));
}
JSONObject agg = new JSONObject();
agg.put("yearmonth", map.get("yearmonth"));
JSONArray queryData1 =new JSONArray();
queryData1.add(agg);
// tt.put("yearmonth",map.get("yearmonth"));
// all.add(tt);
// String yearMonth=(String)map.get("yearmonth");
// JSONObject obj = new JSONObject();
// obj.put("yearmonth", yearMonth) ;
// queryData2.add(obj) ;
// queryData3.put("key",queryData1);
queryData3.put("key",agg);
queryData3.put("value",queryData2);
all.add(queryData3);
}else{
SQLParameter ss1 = new SQLParameter();
StringBuilder sql1 = new StringBuilder();
ss1.clearParams();
sql1.setLength(0);
sql1.append(" SELECT distinct wa.slip_item,wa.item_displayname,wa.showorder FROM wa_payslip_item wa WHERE wa.pk_payslip = '1001ZZ100000000J7IWU' \n");
JSONArray queryData2 = this.queryData2(sql1.toString(),ss1);
JSONObject tt =null;
JSONObject agg = new JSONObject();
for (int j = 0; j < queryData2.size(); j++) {
tt = queryData2.getJSONObject(j);
//tt.put(tt.get("slip_item").toString(), map.get(tt.get("slip_item").toString()));
// tt.put("value", map.get(tt.get("slip_item").toString()));
tt.put("value", map.get(tt.get("slip_item").toString()));
}
// tt.put("yearmonth", map.get("yearmonth"));
// queryData2.add(tt);
agg.put("yearmonth", map.get("yearmonth"));
JSONArray queryData1 =new JSONArray();
queryData1.add(agg);
// tt.put("yearmonth",map.get("yearmonth"));
// all.add(tt);
// String yearMonth=(String)map.get("yearmonth");
// JSONObject obj = new JSONObject();
// obj.put("yearmonth", yearMonth) ;
// queryData2.add(obj) ;
// queryData3.put("key",queryData1);
// queryData3.put("key",agg);
queryData3.put("value",queryData2);
all.add(agg);
all.add(queryData3);
}
}
} catch (BusinessException e) {
ErmBXLogger.getInstance().error("Tools=>queryData2:"+e.getMessage());
ExceptionUtils.wrappException(e);
}
return all;*/
BaseDAO bs = new BaseDAO();
JSONArray all = new JSONArray();
List<Map<String, Object>> bList = null ;
try {
if(ss==null){
bList = (List<Map<String, Object>>) bs.executeQuery(sql,new MapListProcessor());
}else{
bList = (List<Map<String, Object>>) bs.executeQuery(sql,ss,new MapListProcessor());
}
for (int i = 0; i < bList.size(); i++) {
Map<String, Object> map = bList.get(i);//第N条数据
//1、获取当前数据是否在编
List<Map<String, Object>> Listshow = null;
String bianzi = (String)map.get("bianzhi");
if("正编".equals(bianzi)){
SQLParameter ss1 = new SQLParameter();
StringBuilder sql1 = new StringBuilder();
ss1.clearParams();
sql1.setLength(0);
sql1.append(" SELECT wa.slip_item,wa.item_displayname,wa.showorder FROM wa_payslip_item wa WHERE wa.pk_payslip = '1001ZZ100000000MVC1M' \n");
JSONArray queryData2 = this.queryData2(sql1.toString(),ss1);
for (int j = 0; j < queryData2.size(); j++) {
JSONObject tt = queryData2.getJSONObject(j);
tt.put("value", map.get(tt.get("slip_item").toString()));
}
String year=(String)map.get("cyear");//年
String month=(String)map.get("cperiod");//月
JSONObject obj = new JSONObject();
obj.put("saly", queryData2);
obj.put("year", year);
obj.put("month", month);
// Listshow.add(map1);
all.add(obj);
System.out.println("1111111");
}else{
SQLParameter ss1 = new SQLParameter();
StringBuilder sql1 = new StringBuilder();
ss1.clearParams();
sql1.setLength(0);
sql1.append(" SELECT wa.slip_item,wa.item_displayname,wa.showorder FROM wa_payslip_item wa WHERE wa.pk_payslip = '1001ZZ100000000J7IWU' \n");
JSONArray queryData2 = this.queryData2(sql1.toString(),ss1);
for (int j = 0; j < queryData2.size(); j++) {
JSONObject tt = queryData2.getJSONObject(j);
//tt.put(tt.get("slip_item").toString(), map.get(tt.get("slip_item").toString()));
tt.put("value", map.get(tt.get("slip_item").toString()));
}
// all.add(queryData2); 原来的代码
String year=(String)map.get("cyear");//年
String month=(String)map.get("cperiod");//月
JSONObject obj = new JSONObject();
obj.put("saly", queryData2);
obj.put("year", year);
obj.put("month", month);
// Listshow.add(map1);
all.add(obj);
}
}
} catch (BusinessException e) {
ErmBXLogger.getInstance().error("Tools=>queryData2:"+e.getMessage());
ExceptionUtils.wrappException(e);
}
return all;
}