JavaWeb学习的第十九天(Ajax_JSON)

半世苍凉 提交于 2020-01-10 20:22:59

一、Ajax的基本介绍和原生JS实现Ajax的步骤

1.ajax的基本介绍

AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
AJAX 最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。


2.同步请求和异步请求

同步:一个一个串行执行
异步:同时执行
异步请求:
   特点:在请求响应的过程中,浏览器能够继续操作,不需要等待服务器的响应
   请求响应回来之后不需要重新加载整个网页,实现网页的局部刷新
同步请求:表单,链接
   特点:只要发送请求,整个页面内容都会重新加载
   请求发送出去之后必须要等待服务器响应回来之后才能继续操作

注意:XMLHttpRequest是AJAX的基础。

3.JS对象发送异步请求的方式

3.1 创建 XMLHttpRequest 对象
var xmlhttp;
if (window.XMLHttpRequest)
{
    //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
    xmlhttp=new XMLHttpRequest();
}
else
{
    // IE6, IE5 浏览器执行代码
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//2.建立连接
xmlhttp.open("GET","/ajaxServlet?username=Jerry",true) //true为异步
//3.发送请求
xmlhttp.send();

//4.监听服务器响应数据完毕的状态变化
xmlhttp.onreadystatechange=function(){
   if(xmlhttp.readyState==4&&xmlhttp.status==200){
       document.getElementById("div1").innerHTML=xmlhttp.responseText;
   }else {
       document.getElementById("div1").innerHTML=xmlhttp.responseText;
   }
}


二、使用代码完成一次异步请求,并向浏览器的html页面响应内容

1.新建一个html页面,实现如下代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function createxmlHttp(){
            var xmlhttp;
            if(window.XMLHttpRequest){
                xmlhttp=new XMLHttpRequest();
            }else{
                xmlhttp=new ActiveXObject();
            }
            return xmlhttp;
        }

        window.onload=function () {
            document.getElementById("btn1").onclick=function () {
                //1.创建xmlhttprequest对象
                var xmlhttp = createxmlHttp();
                //2.建立连接
                xmlhttp.open("GET","/ajaxServlet?username=Jerry",true) //true为异步
                //3.发送请求
                xmlhttp.send();
                //4.监听服务器响应数据完毕的状态变化
                xmlhttp.onreadystatechange=function(){
                    if(xmlhttp.readyState==4&&xmlhttp.status==200){
                        document.getElementById("div1").innerHTML=xmlhttp.responseText;
                    }else {
                        document.getElementById("div1").innerHTML=xmlhttp.responseText;
                    }
                }
            }
            document.getElementById("btn2").onclick=function () {
                //1.创建xmlhttprequest对象
                var xmlhttp = createxmlHttp();
                //2.建立连接
                xmlhttp.open("POST","/ajaxServlet",true) //true为异步
                //3.发送请求
                xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                xmlhttp.send("username=tom");
            }
        }
    </script>
</head>
<body>
    <button id="btn1">发送get异步请求</button><br>
    <button id="btn2">发送post异步请求</button><br>
    <input type="text"><br>
    <div id="div1">

    </div>
</body>
</html>




2.在src下新建一个AjaxServlet

package com.bianyiit.web;

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.Map;

@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println(username+":ajaxServlet被访问了");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

3.启动tomcat,效果演示


三、JQuery对象实现异步请求常用的三种方式

1.JQuery对象发送异步请求常用的三种方式:$.ajax $.get $.post
2.$.ajax发送异步请求

$("#btn1").click(function () {
    $.ajax({
        url:"/ajaxServlet1",
        type:"get",
        data:"username=fox",
        async:true,
        dataType:"text",  //指定服务器响应回来的数据格式,如果不指定,默认根据服务器响应的MIME Type去智能判断
        success:function (data) {
            $("#div1").html(data);
        },
		dataType:"text"
		//指定服务器响应回来的数据格式,如果不指定,默认根据服务器响应的MIME Type去智能判断
    })
})

3.$.get发送异步请求

$("#btn1").click(function () {
    $.get(
        "/ajaxServlet1",
        {
            username:"jerry",
            password:"12345",
        },
        function (data) {
            $("#div1").html(data)
        },
        dataType:"text"
		//指定服务器响应回来的数据格式,如果不指定,默认根据服务器响应的MIME Type去智能判断
    )
})

4.$.post发送异步请求

$("#btn2").click(function () {
    $.post(
        "/ajaxServlet1",
        {
            username:"jerry",
            password:"12345",
        },
        function (data) {
            $("#div1").html(data)
        },
        dataType:"text"
		//指定服务器响应回来的数据格式,如果不指定,默认根据服务器响应的MIME Type去智能判断
    )
})

4.获取数据后直接在div中显示数据内容

$(function () {
   $("#div1").load("/ajaxServlet")
})

Jquery对象发送异步请求常用的三种方式的区别

1.$.ajax是jquery发送异步请求的基本方式
  $.ajax能够设置http请求的各种请求信息
2.$.get和$.post是基于$.ajax封装的更加简单的异步请求方式
  $.get和$.post只能发送普通的表单类型请求
四、分别使用$.ajax $.get $.post完成一次异步请求,并向浏览器的html页面响应内容

1.新建一个html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-1.11.0.js"></script>
    <script>
        /**
         * 1.请求方式
         * 2.请求路径
         * 3.请求参数
         * 4.响应数据
         */
        $(function () {
            $("#btn1").click(function () {
                $.ajax({
                    url:"/ajaxServlet1",
                    type:"get",
                    data:"username=fox",
                    async:true,
                    dataType:"text",  //指定服务器响应回来的数据格式,如果不指定,默认根据服务器响应的MIME Type去智能判断
                    success:function (data) {
                        $("#div1").html(data);
                    },
                })
            })
            $("#btn2").click(function () {
                $.get(
                    "/ajaxServlet1",
                    /*不加引号只传输请求参数,不加引号传输的是完整的json对象*/
                    {
                        username:"tom",
                        password:"12345",
                    },
                    function (data) {
                        $("#div1").html(data)
                    }
                )
            })
            $("#btn3").click(function () {
                $.post(
                    "/ajaxServlet1",
                    /*不加引号只传输请求参数,不加引号传输的是完整的json对象*/
                    {
                        username:"jerry",
                        password:"78945",
                    },
                    function (data) {
                        $("#div1").html(data)
                    }
                )
            })
        })
    </script>
</head>
<body>
    <button id="btn1">使用Ajax发送异步请求</button><br>
    <button id="btn2">使用get发送异步请求</button><br>
    <button id="btn3">使用post发送异步请求</button><br>
    <input type="text"><br>
    <div id="div1">

    </div>
</body>
</html>

2.创建一个AjaxServlet

package com.bianyiit.web;

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("/ajaxServlet1")
public class AjaxServlet1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+":"+password);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(username+":"+password);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

3.启动tomcat,效果演示



五、JSON的基本介绍

1.JSON的基本介绍

Json存储数据(作为在网络中传输数据的数据交换一种格式)


2.json字符串的写法

json数据格式分为2种
	1.json对象
	2.json数组(集合)

2.1 json对象

<script>
	var user1={
	    id:1,
	    username:"tom",
	    password:"12345"
	}
	console.log(user1.id,user1.username,user1.password)
</script>


2.2 单列集合or数组

<script>
	var arr=new Array(3);
	arr[0]="zs"
	arr[1]="ls"
	arr[2]="ww"
	for (var i = 0; i < arr.length ; i++) {
	    console.log(arr[i]);
	}
	console.log(arr);
</script>


2.3 json对象和json数组混用1

<script>
	var user1={
	    id:1,
	    username:"tom",
	    password:"12345"
	}
	var user2={
	    id:1,
	    username:"jerry",
	    password:"78945"
	}
	var user3={
	    id:1,
	    username:"dog",
	    password:"45612"
	}
	var jsonArr=[
	    user1,
	    user2,
	    user3,
	]
	console.log(jsonArr)
</script>


json表示数组对象的简写形式

<script>
	var jsonArr1=[
	   {id:1, username:"tom", password:"123"},
	   {id:2, username:"jerry", password:"456"},
	   {id:3, username:"dog", password:"789"},
	]
	console.log(jsonArr1);
</script>


2.4 json对象和json数组混用2

<script>
	var jsonArr2={
	    id:1,
	    username:"tom",
	    password:"12345",
	    hobbys:["java","php","html"]
	}
	console.log(jsonArr2);
</script>

六、java对象和json对象的相互转换

1.为什么要让java对象和json对象相互转换??

因为我们在Servlet中一般是使用java对象封装属性的,而要解析java对象需要用到JVM虚拟机,而一般的用户电脑上只有一个浏览器,浏览器的也都是html页面
我们发送一个java对象过去,用户电脑上并没有JVM可以去解析这个java对象
而json是浏览器可以去解析的对象,通过将java对象转换成json对象就可以传输到用户的浏览器上,而我们可以解析json对象,输入里面的相关信息

2.如何解析json对象--通过json解析引擎

jsonlib
Gson (google提供,一般用在Android中)  
fastJson(阿里巴巴,号称全世界做好做快的json解析引擎) 
Jackson(springmvc无缝对接)

3.Jackson的基本使用

1.导入jar包
2.创建objectMapper对象
3.通过objectMapper上面的方法完成json的转换
	3.1 writeValueAsString,将对象转换成json字符串并返回
	3.2 writeValue方法可以将对象转换成json字符串并且通过制定的输出流把json字符串输出到指定位置
	3.3 readValue(jsonUser,User.class),可以将json字符串转换成java对象
链接:https://pan.baidu.com/s/1sNs_RHi8cRYAw7hIvS9Cyg 
提取码:yj22 
复制这段内容后打开百度网盘手机App,操作更方便哦

4.java对象转换成json对象的代码演示

package com.bianyiit.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday='" + birthday + '\'' +
                '}';
    }
}
package com.bianyiit.json;

import com.bianyiit.domain.User;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Date;

public class JsonTest {
    public static void main(String[] args) throws IOException {
        User user=new User();
        user.setId(1);
        user.setUsername("tom");
        user.setPassword("12345");
        user.setBirthday(new Date());
        //使用步骤
        ObjectMapper mapper1=new ObjectMapper();
        String userJson=mapper1.writeValueAsString(user);
        System.out.println(userJson);
    }
}


java对象转换成json对象并通过流输出的常用方式

package com.bianyiit.json;

import com.bianyiit.domain.User;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Date;

public class JsonTest {
    public static void main(String[] args) throws IOException {
        User user=new User();
        user.setId(1);
        user.setUsername("tom");
        user.setPassword("12345");
        user.setBirthday(new Date());
        //使用步骤
        ObjectMapper mapper1=new ObjectMapper();
        //先将java对象转换成json对象,然后再通过流输出
        mapper1.writeValue(System.out,user);
    }
}

由于日期输出的是毫秒值,而且我们一般希望密码不封装进json对象中

/*忽略这个字段,在转json字符串的时候,加上这个注解的字段不会被转换到json中*/
@JsonIgnore
private String password;
/*设置当前当前字段转换的一个基本日期格式*/
@JsonFormat(pattern="yyyy-MM-dd")
private Date birthday;

5.json对象转换成java对象的代码演示

package com.bianyiit.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class User {
    private int id;
    private String username;
    /*忽略这个字段,在转json字符串的时候,加上这个注解的字段不会被转换到json中*/
    @JsonIgnore
    private String password;
    /*设置当前当前字段转换的一个基本日期格式*/
    @JsonFormat(pattern="yyyy-MM-dd")
    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday='" + birthday + '\'' +
                '}';
    }
}
package com.bianyiit.json;

import com.bianyiit.domain.User;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
public class JsonTest {
    public static void main(String[] args) throws IOException {
        User user=new User();
         /*json对象转换成java对象*/
        String jsonUser="{\"id\":1,\"username\":\"tom\",\"birthday\":\"2020-01-09\"}";
        ObjectMapper mapper2=new ObjectMapper();
        User user2=mapper2.readValue(jsonUser,User.class);
        System.out.println(user2);
    }
}


4.Fastjson基本使用

1.导入jar包
2.String jsouUser= JSON.toJSONString(user) 将java对象转换成json字符串并返回
3.User user=JSON.parseObject(jsonUser,User.class) 将json字符串转换成java对象
链接:https://pan.baidu.com/s/1wQNrHT8kFIZl3dqi_IKB5A 
提取码:zn7m

4.java对象转换成json对象的代码演示

package com.bianyiit.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday='" + birthday + '\'' +
                '}';
    }
}
package com.bianyiit.json;

import com.alibaba.fastjson.JSON;
import com.bianyiit.domain.User;
import org.junit.Test;

import java.util.Date;

public class JSonTest2 {
    @Test
    public void java2Json(){
        User user=new User();
        user.setId(1);
        user.setUsername("tom");
        user.setPassword("12345");
        user.setBirthday(new Date());
        String jsouUser= JSON.toJSONString(user);
        System.out.println(jsouUser);
    }
}


4.json对象转换成java对象的代码演示

package com.bianyiit.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday='" + birthday + '\'' +
                '}';
    }
}
package com.bianyiit.json;

import com.alibaba.fastjson.JSON;
import com.bianyiit.domain.User;
import org.junit.Test;

import java.util.Date;

public class JSonTest2 {
    @Test
    public void json2Java(){
        String jsonUser="{\"id\":1,\"username\":\"tom\",\"birthday\":\"2020-01-09\"}";
        User user=JSON.parseObject(jsonUser,User.class);
        System.out.println(user);
    }
}

案例一:异步校验用户名是否可用

1.新建一个register.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>网站注册页面</title>
    <style>
        #contanier{
            border: 0px solid white;
            width: 1300px;
            margin: auto;
        }
        #form{
            height: 500px;
            padding-top: 70px;
            margin-bottom: 10px;
        }
        a{
            text-decoration: none;
        }
       .error{
            font-family:georgia;
            font-size: 15px;
            font-style: normal;
            color: red;
        }
        #father{
            border: 0px solid white;
            padding-left: 307px;
        }
        #form2{
            border: 5px solid gray;
            width: 660px;
            height: 450px;
        }
    </style>
    <script src="js/jquery-1.11.0.js"></script>
    <script>
        $(function () {
            $("#user").blur(function () {
                // 2.获取用户输入的用户名
                var username = $("#user").val();
                $.get("/userServlet",{username:username},function (data) {
                    if (data.flag){
                        $("#errorMsg_username").removeClass("error")
                        $("#errorMsg_username").empty();
                    } else {
                        $("#errorMsg_username").addClass("error")
                        $("#errorMsg_username").html(data.msg)
                    }
                },"json");
            })
        })
    </script>
</head>
<body>
<div id="contanier">
    <div id="form">
        <form action="#" method="get" id="registForm">
            <div id="father">
                <div id="form2">
                    <table border="0px" width="100%" height="100%" align="center" cellpadding="0px" cellspacing="0px" bgcolor="white">
                        <tr align="center">
                            <td colspan="2" >
                                <font size="5">会员注册</font>&nbsp;&nbsp;&nbsp;
                            </td>
                        </tr>
                        <tr align="center">
                            <td width="180px">
                                <label for="user" >用户名</label>
                            </td>
                            <td>
                                <em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                <input type="text" name="user" size="35px" id="user"/>
                                <span id="errorMsg_username"></span>
                            </td>
                        </tr>
                        <tr align="center">
                            <td>
                                密码
                            </td>
                            <td>
                                <em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                <input type="password"  name="password" size="35px" id="password" />
                                <span id="errorMsg_password"></span>
                            </td>
                        </tr>
                        <tr align="center">
                            <td>
                                确认密码
                            </td>
                            <td>
                                <em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                <input type="password" name="repassword" size="35px"/>
                            </td>
                        </tr>
                        <tr align="center">
                            <td>
                                Email
                            </td>
                            <td>
                                <em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                <input type="text" name="email" size="35px" id="email"/>
                            </td>
                        </tr>
                        <tr align="center">
                            <td>
                                姓名
                            </td>
                            <td>
                                <em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                <input type="text" name="username" size="35px"/>
                            </td>
                        </tr>
                        <tr align="center">
                            <td>
                                性别
                            </td>
                            <td>
										<span style="margin-right: 155px;">
											<em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                            <input type="radio" name="sex" value="男"/>男
											<input type="radio" name="sex" value="女"/>女<em></em>


										</span>

                            </td>
                        </tr>
                        <tr  align="center">
                            <td>
                                出生日期
                            </td>
                            <td>
                                <em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                <input type="text" name="birthday"  size="35px"/>
                            </td>
                        </tr>

                        <tr  align="center">
                            <td colspan="2">
                                <input id="btn_form" type="button" value="注      册" height="50px"/>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </form>
    </div>
</div>
</body>
</html>



2.新建一个User类

package com.bianyiit.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class User {
    private int id;
    private String username;
    /*忽略这个字段,在转json字符串的时候,加上这个注解的字段不会被转换到json中*/
    @JsonIgnore
    private String password;
    /*设置当前当前字段转换的一个基本日期格式*/
    @JsonFormat(pattern="yyyy-MM-dd")
    private Date birthday;
    private String sex;
    private String email;

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

3.新建一个ResultInfo类,里面包含一个boolean值用来标识是否存在用户,一个msg用来输出错误信息

package com.bianyiit.domain;

public class ResultInfo {
    private boolean flag;
    private String msg;
    public boolean isFlag() {
        return flag;
    }
    public void setFlag(boolean flag) {
        this.flag = flag;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    @Override
    public String toString() {
        return "ResultInfo{" +
                "flag=" + flag +
                ", msg='" + msg + '\'' +
                '}';
    }
}

4.新建一个UserServlet

package com.bianyiit.web;

import com.bianyiit.domain.ResultInfo;
import com.bianyiit.domain.User;
import com.bianyiit.service.UserService;
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;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //1.获取请求参数
        String username = request.getParameter("username");
        //2.调用service完成业务逻辑
        UserService userService = new UserService();
        User user=userService.checkUser(username);
        System.out.println(user);
        //3.根据业务处理结果响应数据
        ResultInfo resultInfo = new ResultInfo();
        if(user==null){
            resultInfo.setFlag(false);
            resultInfo.setMsg("用户名不存在!!");
        }else {
            resultInfo.setFlag(true);
            resultInfo.setMsg("用户名已存在!!");
        }
        System.out.println(resultInfo);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(response.getWriter(),resultInfo);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

5.新建一个UserService

package com.bianyiit.service;

import com.bianyiit.dao.UserDao;
import com.bianyiit.domain.User;

public class UserService {
    UserDao userDao = new UserDao();
    public User checkUser(String username) {
       return userDao.checkUser(username);
    }
}

6.新建一个UserDao

package com.bianyiit.dao;

import com.bianyiit.domain.User;
import com.bianyiit.util.JdbcUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

public class UserDao {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(JdbcUtils.getDataSource());
    public User checkUser(String username) {
        String sql="select * from usermsg where username=?";
        User user = null;
        try {
            user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username);
        } catch (DataAccessException e) {
            //e.printStackTrace();
        }
        return user;
    }
}

7.效果演示


案例二:提供注册表单,通过ajax请求提交表单数据保存用户信息到数据库中

1.新建一个register.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>网站注册页面</title>
    <style>
        #contanier{
            border: 0px solid white;
            width: 1300px;
            margin: auto;
        }
        #form{
            height: 500px;
            padding-top: 70px;
            margin-bottom: 10px;
        }
        a{
            text-decoration: none;
        }
       .error{
            font-family:georgia;
            font-size: 15px;
            font-style: normal;
            color: red;
        }
        #father{
            border: 0px solid white;
            padding-left: 307px;
        }
        #form2{
            border: 5px solid gray;
            width: 660px;
            height: 450px;
        }
    </style>
    <script src="js/jquery-1.8.3.js"></script>
    <script>
        $(function () {
            $("#btn_form").click(function () {
                $.post("/maven_web1/registerServlet",$("#registForm").serialize(),function (data) {
                    if($(data.flag)){
                        location.href="/maven_web1/index.html"
                    }else {
                        alert("注册失败")
                    }
                })
            })
            $("#user").blur(function () {
                // 2.获取用户输入的用户名
                var username = $("#user").val();
                $.get("/maven_web1/userServlet",{username:username},function (data) {
                    if (data.flag){
                        $("#errorMsg_username").removeClass("error")
                        $("#errorMsg_username").empty();
                    } else {
                        $("#errorMsg_username").addClass("error")
                        $("#errorMsg_username").html(data.msg)
                    }
                },"json");
            })
        })
    </script>
</head>
<body>
<div id="contanier">
    <div id="form">
        <form action="#" method="get" id="registForm">
            <div id="father">
                <div id="form2">
                    <table border="0px" width="100%" height="100%" align="center" cellpadding="0px" cellspacing="0px" bgcolor="white">
                        <tr align="center">
                            <td colspan="2" >
                                <font size="5">会员注册</font>&nbsp;&nbsp;&nbsp;
                            </td>
                        </tr>
                        <tr align="center">
                            <td width="180px">
                                <label for="user" >用户名</label>
                            </td>
                            <td>
                                <em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                <input type="text" name="user" size="35px" id="user"/>
                                <span id="errorMsg_username"></span>
                            </td>
                        </tr>
                        <tr align="center">
                            <td>
                                密码
                            </td>
                            <td>
                                <em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                <input type="password"  name="password" size="35px" id="password" />
                                <span id="errorMsg_password"></span>
                            </td>
                        </tr>
                        <tr align="center">
                            <td>
                                确认密码
                            </td>
                            <td>
                                <em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                <input type="password" name="repassword" size="35px"/>
                            </td>
                        </tr>
                        <tr align="center">
                            <td>
                                Email
                            </td>
                            <td>
                                <em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                <input type="text" name="email" size="35px" id="email"/>
                            </td>
                        </tr>
                        <tr align="center">
                            <td>
                                姓名
                            </td>
                            <td>
                                <em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                <input type="text" name="username" size="35px"/>
                            </td>
                        </tr>
                        <tr align="center">
                            <td>
                                性别
                            </td>
                            <td>
										<span style="margin-right: 155px;">
											<em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                            <input type="radio" name="sex" value="男"/>男
											<input type="radio" name="sex" value="女"/>女<em></em>


										</span>

                            </td>
                        </tr>
                        <tr  align="center">
                            <td>
                                出生日期
                            </td>
                            <td>
                                <em style="color: red;">*</em>&nbsp;&nbsp;&nbsp;
                                <input type="text" name="birthday"  size="35px"/>
                            </td>
                        </tr>

                        <tr  align="center">
                            <td colspan="2">
                                <input id="btn_form" type="button" value="注      册" height="50px"/>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </form>
    </div>
</div>
</body>
</html>

2.新建一个User类

package com.bianyiit.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class User {
    private int id;
    private String username;
    /*忽略这个字段,在转json字符串的时候,加上这个注解的字段不会被转换到json中*/
    @JsonIgnore
    private String password;
    /*设置当前当前字段转换的一个基本日期格式*/
    @JsonFormat(pattern="yyyy-MM-dd")
    private Date birthday;
    private String sex;
    private String email;

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

3.新建一个ResultInfo类,里面包含一个boolean值用来标识是否存在用户,一个msg用来输出错误信息

package com.bianyiit.domain;

public class ResultInfo {
    private boolean flag;
    private String msg;
    public boolean isFlag() {
        return flag;
    }
    public void setFlag(boolean flag) {
        this.flag = flag;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    @Override
    public String toString() {
        return "ResultInfo{" +
                "flag=" + flag +
                ", msg='" + msg + '\'' +
                '}';
    }
}

4.新建一个RegisterServlet

package com.bianyiit.web;

import com.bianyiit.domain.ResultInfo;
import com.bianyiit.domain.User;
import com.bianyiit.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;

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.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user=new User();
        try {
            BeanUtils.populate(user,parameterMap);
            System.out.println(user);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        ResultInfo resultInfo = new ResultInfo();
        try {
            new UserService().addUser(user);
            resultInfo.setFlag(true);
        }catch (Exception e){
            resultInfo.setFlag(false);
        }
        System.out.println(resultInfo);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(response.getWriter(),resultInfo);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

5.新建UserService

package com.bianyiit.service;

import com.bianyiit.dao.UserDao;
import com.bianyiit.domain.User;

public class UserService {
    UserDao userDao = new UserDao();
    public User checkUser(String username) {
       return userDao.checkUser(username);
    }

    public void addUser(User user) {
        userDao.addUser(user);
    }
}

6.新建一个UserDao

package com.bianyiit.dao;

import com.bianyiit.domain.User;
import com.bianyiit.util.JdbcUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

public class UserDao {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(JdbcUtils.getDataSource());
    public User checkUser(String username) {
        String sql="select * from usermsg where username=?";
        User user = null;
        try {
            user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username);
        } catch (DataAccessException e) {
            //e.printStackTrace();
        }
        return user;
    }

    public int addUser(User user) {
        String sql="insert into usermsg values(null,?,?,?,?,?)";
        int update = jdbcTemplate.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getSex(),
                user.getBirthday(),
                user.getEmail());
        return update;
    }
}

7.效果演示


案例三:异步获取所有用户信息

1.新建一个userlist.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-1.11.0.js"></script>
    <script>
        $(function () {
            $("#findAll").click(function () {
                $.get("/maven_web1/findAllServlet",{},function (data) {
                    $("#userlist_table").empty();
                    $("#userlist_table").html("<tr>\n" +
                        "        <th>用户编号</th>\n" +
                        "        <th>用户名称</th>\n" +
                        "        <th>用户密码</th>\n" +
                        "        <th>性别</th>\n" +
                        "        <th>生日</th>\n" +
                        "        <th>邮箱</th>\n" +
                        "    </tr>")

                    $.each(data,function (i,user) {

                        var tr = " <tr>\n" +
                        "        <td>"+(i+1)+"</td>\n" +
                        "        <td>"+user.username+"</td>\n" +
                        "        <td>"+user.password+"</td>\n" +
                        "        <td>"+user.sex+"</td>\n" +
                        "        <td>"+user.birthday+"</td>\n" +
                        "        <td>"+user.email+"</td>\n" +
                        "    </tr>"
                       $("#userlist_table").append(tr)
                    })

                })
            })
        })
    </script>
</head>
<body>
<button id="findAll">获取所有用户信息</button>
<table id="userlist_table" border="1px" width="1000px" cellspacing="0px" cellpadding="0px" align="center">
    <tr>
        <th>用户编号</th>
        <th>用户名称</th>
        <th>用户密码</th>
        <th>性别</th>
        <th>生日</th>
        <th>邮箱</th>
    </tr>
</table>
</body>
</html>

2.新建一个User类

package com.bianyiit.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class User {
    private int id;
    private String username;
    /*忽略这个字段,在转json字符串的时候,加上这个注解的字段不会被转换到json中*/
    @JsonIgnore
    private String password;
    /*设置当前当前字段转换的一个基本日期格式*/
    @JsonFormat(pattern="yyyy-MM-dd")
    private Date birthday;
    private String sex;
    private String email;

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

3.新建一个ResultInfo类,里面包含一个boolean值用来标识是否存在用户,一个msg用来输出错误信息

package com.bianyiit.domain;

public class ResultInfo {
    private boolean flag;
    private String msg;
    public boolean isFlag() {
        return flag;
    }
    public void setFlag(boolean flag) {
        this.flag = flag;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    @Override
    public String toString() {
        return "ResultInfo{" +
                "flag=" + flag +
                ", msg='" + msg + '\'' +
                '}';
    }
}

4.新建一个FindAllServlet

package com.bianyiit.web;

import com.bianyiit.domain.User;
import com.bianyiit.service.UserService;
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.List;

@WebServlet("/findAllServlet")
public class FindAllServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        UserService userService = new UserService();
        List<User> userList = userService.findAll();

        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(response.getWriter(),userList);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

5.新建UserService

package com.bianyiit.service;

import com.bianyiit.dao.UserDao;
import com.bianyiit.domain.User;

import java.util.List;

public class UserService {
    UserDao userDao = new UserDao();
    public User checkUser(String username) {
       return userDao.checkUser(username);
    }

    public void addUser(User user) {
        userDao.addUser(user);
    }

    public List<User> findAll() {
        return userDao.findAll();
    }
}

6.新建一个UserDao

package com.bianyiit.dao;

import com.bianyiit.domain.User;
import com.bianyiit.util.JdbcUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDao {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(JdbcUtils.getDataSource());
    public User checkUser(String username) {
        String sql="select * from usermsg where username=?";
        User user = null;
        try {
            user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username);
        } catch (DataAccessException e) {
            //e.printStackTrace();
        }
        return user;
    }

    public int addUser(User user) {
        String sql="insert into usermsg values(null,?,?,?,?,?)";
        int update = jdbcTemplate.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getSex(),
                user.getBirthday(),
                user.getEmail());
        return update;
    }

    public List<User> findAll() {
        String sql="select * from usermsg";
        List<User> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
        return query;
    }
}

7.效果演示

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!