💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# :-: 用户名校验案例 ## 一、创建动态web项目,名称为AjaxJson 项目目录结构如下: ![](http://h.yiniuedu.com/94922cbfd5086692a951dd10bca54902) >首先导入jar包,资源下载: 1.[本次用到JSON的jar包链接: ](http://h.yiniuedu.com/jackson.zip) 2.[本次js下载]链接: https://pan.baidu.com/s/1qOs5C_GCc2XJmEO_QguA8g 提取码: xm3t 3.其他包下载链接: https://pan.baidu.com/s/11Mf_mlpg43g3R5OPQZmnhQ 提取码: 5wcf ### 1.创建包cn.baishenghua.domain,在该包下创建类Person,代码如下: ``` package cn.baishenghua.domain; import com.fasterxml.jackson.annotation.JsonFormat; 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 + '\'' + '}'; } } ``` ### 2.创建包cn.baishenghua.test,然后在该包下创建测试类JacksonTest,代码如下 ``` package cn.baishenghua.test; import cn.baishenghua.domain.Person; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.FileWriter; import java.util.*; public class JacksonTest { //Java对象转为JSON字符串 @Test public void test1() throws Exception { //1.创建Person对象 Person p = new Person(); p.setName("张三"); p.setAge(23); p.setGender("男"); //2.创建Jackson的核心对象 ObjectMapper ObjectMapper mapper = new ObjectMapper(); //3.转换 /* 转换方法: writeValue(参数1,obj): 参数1: File:将obj对象转换为JSON字符串,并保存到指定的文件中 Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中 OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中 writeValueAsString(obj):将对象转为json字符串 */ String json = mapper.writeValueAsString(p); //{"name":"张三","age":23,"gender":"男"} //System.out.println(json);//{"name":"张三","age":23,"gender":"男"} //writeValue,将数据写到d://a.txt文件中 //mapper.writeValue(new File("d://a.txt"),p); //writeValue.将数据关联到Writer中 mapper.writeValue(new FileWriter("d://b.txt"),p); } @Test public void test2() throws Exception { //1.创建Person对象 Person p = new Person(); p.setName("张三"); p.setAge(23); p.setGender("男"); p.setBirthday(new Date()); //2.转换 ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(p); System.out.println(json);//{"name":"张三","age":23,"gender":"男","birthday":1530958029263} //{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"} } @Test public void test3() throws Exception { //1.创建Person对象 Person p = new Person(); p.setName("张三"); p.setAge(23); p.setGender("男"); p.setBirthday(new Date()); Person p1 = new Person(); p1.setName("张三"); p1.setAge(23); p1.setGender("男"); p1.setBirthday(new Date()); Person p2 = new Person(); p2.setName("张三"); p2.setAge(23); p2.setGender("男"); p2.setBirthday(new Date()); //创建List集合 List<Person> ps = new ArrayList<Person>(); ps.add(p); ps.add(p1); ps.add(p2); //2.转换 ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(ps); // [{},{},{}] //[{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"},{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"},{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"}] System.out.println(json); } @Test public void test4() throws Exception { //1.创建map对象 Map<String,Object> map = new HashMap<String,Object>(); map.put("name","张三"); map.put("age",23); map.put("gender","男"); //2.转换 ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(map); //{"name":"张三","age":23,"gender":"男"} System.out.println(json);//{"gender":"男","name":"张三","age":23} } //演示 JSON字符串转为Java对象 @Test public void test5() throws Exception { //1.初始化JSON字符串 String json = "{\"gender\":\"男\",\"name\":\"张三\",\"age\":23}"; //2.创建ObjectMapper对象 ObjectMapper mapper = new ObjectMapper(); //3.转换为Java对象 Person对象 Person person = mapper.readValue(json, Person.class); System.out.println(person); } } ``` ### 3.创建包cn.baishenghua.web.servlet,在该包下创建Servlet类AjaxServlet和FindUserServlet。代码如下: ``` package cn.baishenghua.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 { //1.获取请求参数 String username = request.getParameter("username"); /* //处理业务逻辑。耗时 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); }*/ //2.打印username System.out.println(username); //3.响应 response.getWriter().write("hello : " + username); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } } ``` **FindUserServlet.java** ``` package cn.baishenghua.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); } } ``` ## 二、前端界面设计 先导入js 然后创建8个页面 1.01-原生js实现ajax.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> //定义方法 function fun() { //发送异步请求 //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); } } } </script> </head> <body> <input type="button" value="发送异步请求" onclick="fun();"> <input> </body> </html> ``` 2.02_JQuery实现方式1_ajax.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery-3.3.1.min.js"></script> <script> //定义方法 function fun() { //使用$.ajax()发送异步请求 $.ajax({ url:"ajaxServlet" , // 请求路径 type:"POST" , //请求方式 //data: "username=jack&age=23",//请求参数 data:{"username":"jack","age":23}, success:function (data) { alert(data); },//响应成功后的回调函数 error:function () { alert("出错啦...") },//表示如果请求响应出现错误,会执行的回调函数 dataType:"text"//设置接受到的响应数据的格式 }); } </script> </head> <body> <input type="button" value="发送异步请求" onclick="fun();"> <input> </body> </html> ``` 3.03_JQuery实现方式2_get.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery-3.3.1.min.js"></script> <script> //定义方法 function fun() { $.get("ajaxServlet",{username:"rose"},function (data) { alert(data); },"text"); } </script> </head> <body> <input type="button" value="发送异步请求" onclick="fun();"> <input> </body> </html> ``` 4.04_JQuery实现方式3_post.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery-3.3.1.min.js"></script> <script> //定义方法 function fun() { $.post("ajaxServlet",{username:"rose"},function (data) { alert(data); },"text"); } </script> </head> <body> <input type="button" value="发送异步请求" onclick="fun();"> <input> </body> </html> ``` 5.05_json数据语法.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> //1.定义基本格式 var person = {"name": "张三", age: 23, 'gender': true}; //获取name的值 //var name = person.name; var name = person["name"]; // alert(name); //alert(person); //2.嵌套格式 {}———> [] var persons = { "persons": [ {"name": "张三", "age": 23, "gender": true}, {"name": "李四", "age": 24, "gender": true}, {"name": "王五", "age": 25, "gender": false} ] }; // alert(persons); //获取王五值 var name1 = persons.persons[2].name; // alert(name1); //2.嵌套格式 []———> {} var ps = [{"name": "张三", "age": 23, "gender": true}, {"name": "李四", "age": 24, "gender": true}, {"name": "王五", "age": 25, "gender": false}]; //获取李四值 //alert(ps); alert(ps[1].name); </script> </head> <body> </body> </html> ``` 6.06_json数据语法_遍历.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> //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]); } } </script> </head> <body> </body> </html> ``` 7.07-regist.html ``` <!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> ``` 8.index.jsp ``` <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> $END$ </body> </html> ```