ajax技术和Json (案例------校验用户名是否存在)
1.原生js实现ajax
Html页面代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function fun() {
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.建立连接
xmlhttp.open("GET","ajaxServlet?username=tom",true);
//3.发送请求
xmlhttp.send();
//4.接收并处理来自服务器的响应结果
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var responseText = xmlhttp.responseText;
alert(responseText)
}
}
}
</script>
</head>
<body>
<input type="button" value="发送异步请求" onclick="fun()">
</body>
</html>
Servlet部分代码
package cn.itcast.web.servlet;
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;
@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取请求参数
String username = request.getParameter("username");
//2.打印username
System.out.println(username);
//3.响应
response.getWriter().write("hello:"+ username);
}
}
2.jquery实现ajax
1).$.ajax()
html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-3.3.1.js"></script>
<script>
function fun() {
$.ajax({
url:"ajaxServlet",//请求路径
type:"POST",//请求方式
// data:"username=jack&age=23",//请求参数
data:{"username":"jack","age":23},
success:function (data) {
alert(data)
},//响应成功后的回调函数
})
}
</script>
</head>
<body>
<input type="button" value="发送异步请求" onclick="fun()">
</body>
</html>
servlet页面
package cn.itcast.web.servlet;
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;
@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post请求。。。");
request.getParameter("username");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("get请求。。。");
request.getParameter("username");
}
}
2).$.get()
Html页面 servlet相同
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-3.3.1.js"></script>
<script>
function fun() {
$.get("ajaxServlet",{username:"rose"},function (data) {
alert(data);
},"text");
}
</script>
</head>
<body>
<input type="button" value="发送异步请求" onclick="fun()">
</body>
</html>
3).$.post()
Html页面 servlet相同
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-3.3.1.js"></script>
<script>
function fun() {
$.post("ajaxServlet",{username:"rose"},function (data) {
alert(data);
},"text");
}
</script>
</head>
<body>
<input type="button" value="发送异步请求" onclick="fun()">
</body>
</html>
Json值的获取
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery-3.3.1.js"></script> <script> var person = {"name":"张三","age":23,"gender":true}; var name = person.name;//第一种方法 //var name1 = person["name"];第二种方法 var persons = { "person":[ {"name":"张三","age":23,"gender":true}, {"name":"李四","age":25,"gender":true}, {"name":"王五","age":29,"gender":false} ] }; //获取王五的值 var name2 = persons.person[2].name; alert(name2); var ps = [{"name":"张三","age":23,"gender":true}, {"name":"李四","age":25,"gender":true}, {"name":"王五","age":29,"gender":false}]; //获取李四 var name1 = ps[1].name; alert(name1) </script> </head> <body> <input type="button" value="发送异步请求" onclick="fun()"> </body> </html>
循环key获取value
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-3.3.1.js"></script>
<script>
var person = {"name":"张三","age":23,"gender":true};
var ps = [{"name":"张三","age":23,"gender":true},
{"name":"李四","age":25,"gender":true},
{"name":"王五","age":29,"gender":false}];
//获取person对象所有的键值
for (var key in person){
// alert(key+":"+person[key])
}
for (var item in ps){
var p = ps[item];
for (var key in p) {
alert(key+":"+p[key])
}
}
</script>
</head>
<body>
<input type="button" value="发送异步请求" onclick="fun()">
</body>
</html>
Json数据和Java对象的相互转换
json转换java对象
1.使用步骤
a:导入jackson的相关jar包
b:创建jsckson核心对象ObjectMapper
c:调用ObjectMapper的相关方法进行转换
1.readValue(json字符串数据,class)
package cn.itcast.test;
import cn.itcast.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import sun.nio.cs.ext.MacArabic;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
public class JsonTest {
@Test
public void test2() throws IOException {
//初始化json字符串
String json = "{\"name\":\"张三\",\"age\":23,\"gender\":\"男\",\"birthday\":\"2019-07-19\"}";
//创建bojectmapper对象
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json, Person.class);
System.out.println(person);
}
}
java转换json
1.使用步骤
a:导入jackson的相关jar包
b:创建jsckson核心对象ObjectMapper
c:调用ObjectMapper的相关方法进行转换
转换
* 转换方法:
* writeValue(参数1,obj)
* 参数1:
* File:将obj对象转换为JSON字符串,并保存到指定的文件中
* Writer:将obj对象转换为json字符串,并将json数据填充到字符输出流中
* OutputStream:将obj对象转换为json数据字符串,并将json数据填充到字节输出流中
* writeValueAsString(obj):将对象转换为json字符串
person.java
package cn.itcast.domain;
public class Person {
private String name;
private int age;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
Test.java
package cn.itcast.test;
import cn.itcast.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class JsonTest {
@Test
public void test1() throws IOException {
//创建person对象
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
//创建jackson的核心对象 objectmapper
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(p);
//写入文件
mapper.writeValue(new File("D:\\Probjectjava\\webdemo\\src\\2.txt"),p);
//将数据关联到writer中
mapper.writeValue(new FileWriter("D:\\Probjectjava\\webdemo\\src\\3.txt"),p);
}
}
json注解
package cn.itcast.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Date;
public class Person {
private String name;
private int age;
private String gender;
// @JsonIgnore 直接排除不显示
@JsonFormat(pattern = "yyyy-MM-dd")//显示固定格式的年月日
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
", birthday=" + birthday +
'}';
}
}
package cn.itcast.test;
import cn.itcast.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
public class JsonTest {
@Test
public void test1() throws IOException {
//创建person对象
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
p.setBirthday(new Date());
//创建jackson的核心对象 objectmapper
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(p);
System.out.println(json);
}
}
结果:
{"name":"张三","age":23,"gender":"男","birthday":"2019-07-19"}
java对象转换json_list和map
//数组格式
package cn.itcast.test;
import cn.itcast.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import sun.nio.cs.ext.MacArabic;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
public class JsonTest {
@Test
public void test1() throws IOException {
//创建person对象
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
p.setBirthday(new Date());
Person p1 = new Person();
p1.setName("王五");
p1.setAge(30);
p1.setGender("男");
p1.setBirthday(new Date());
Person p2 = new Person();
p2.setName("李四");
p2.setAge(25);
p2.setGender("女");
p2.setBirthday(new Date());
//创建jackson的核心对象 objectmapper
ArrayList<Person> list = new ArrayList<Person>();
list.add(p);
list.add(p1);
list.add(p2);
//转换
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(list);
System.out.println(json);
}
}
结果:
[{"name":"张三","age":23,"gender":"男","birthday":"2019-07-19"},{"name":"王五","age":30,"gender":"男","birthday":"2019-07-19"},{"name":"李四","age":25,"gender":"女","birthday":"2019-07-19"}]
**********校验用户民是否存在**********
1.服务器响应的数据,在客户端使用时,要想当作json数据格式使用
*$.get()最后一个参数设置为json
*response.setContentType("application/json;charset=gbk");
html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-3.3.1.js"></script>
<script>
//在页面加载完成后
$(function () {
//给user绑定blur事件
$("#username").blur(function () {
//获取文本输入框的值
var username = $("#username").val();
$.get("findServlet",{"username":username},function (data) {
var span = $("#s_username");
if (data.userExsit){
//用户民存在
span.css("color","green");
span.html(data.msg);
}else{
//用户名不存在
span.css("color","red");
span.html(data.msg)
}
},"json")
})
})
</script>
</head>
<body>
<form action="">
<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="注册">
</form>
</body>
</html>
servlet代码
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("/findServlet")
public class FindServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取用户名
String username = request.getParameter("username");
//调用service层判断用户名是否存在
// response.setContentType("text/html;charset=gbk");
Map<String,Object> map = new HashMap<String,Object>();
if ("tom".equals(username)){
//存在
map.put("userExist",true);
map.put("msg","此用户已存在!");
}else{
//不存在
map.put("userExist",false);
map.put("msg","此用户可用!");
}
//将map转为json
ObjectMapper mapper = new ObjectMapper();
//并且传递给客户端
response.setContentType("application/json;charset=gbk");
mapper.writeValue(response.getWriter(),map);
}
}