JavaWeb基础——Ajax

1、Ajax概述

1.1.什么是同步,什么是异步
同步现象:客户端发送请求到服务器端,当服务器返回响应之前,客户端都处于等待 卡死状态
异步现象:客户端发送请求到服务器端,无论服务器是否返回响应,客户端都可以随 意做其他事情,不会被卡死。所用异步访问都是ajax引擎。

1.2.Ajax的运行原理
页面发起请求,会将请求发送给浏览器内核中的Ajax引擎,Ajax引擎会提交请求到 服务器端,在这段时间里,客户端可以任意进行任意操作,直到服务器端将数据返回 给Ajax引擎后,会触发你设置的事件,从而执行自定义的js逻辑代码完成某种页面1 功能。

2、js原生的Ajax技术

ajaxServlet.java

package cn.ctgu.ajax;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ajaxServlet
 */
@WebServlet("/ajaxServlet")
public class ajaxServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        /*try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
        String paramer=request.getParameter("name");

        response.getWriter().write(Math.random()+paramer);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<script type="text/javascript">

    function fn1(){
        //1、创建ajax引擎对象 ---- 所有的操作都是通过引擎对象
        var xmlHttp = new XMLHttpRequest();
        //2、绑定监听 ---- 监听服务器是否已经返回相应数据
        xmlHttp.onreadystatechange = function(){
            if(xmlHttp.readyState=="4"&&xmlHttp.status=="200"){
                //5、接受相应数据
                var res = xmlHttp.responseText;
                document.getElementById("span1").innerHTML = res;
            }
        }
        //3、绑定地址
        xmlHttp.open("GET","../ajaxServlet?name=lisi",true);
        //4、发送请求
        xmlHttp.send();

    }
    function fn2(){
        //1、创建ajax引擎对象 ---- 所有的操作都是通过引擎对象
        var xmlHttp = new XMLHttpRequest();
        //2、绑定监听 ---- 监听服务器是否已经返回相应数据
        xmlHttp.onreadystatechange = function(){
            if(xmlHttp.readyState=="4"&&xmlHttp.status=="200"){
                //5、接受相应数据
                var res = xmlHttp.responseText;
                document.getElementById("span2").innerHTML = res;
            }
        }
        //3、绑定地址
        xmlHttp.open("POST","../ajaxServlet",false);
        //4、发送请求
        xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//设置了这个头,通过post方式传递的数据才能被servlet接收到
        xmlHttp.send("name=wangwu");

    }


</script>

</head>
<body>
    <input type="button" value="异步访问服务器端" onclick="fn1()"><span id="span1"></span>
    <br>
    <input type="button" value="同步访问服务器端" onclick="fn2()"><span id="span2"></span>
    <br>
    <input type="button" value="测试按钮" onclick="alert()">
</body>
</html>

3、Jquery的Ajax技术
jquery是一个优秀的js框架,自然对js原生的ajax进行了封装,封装后的ajax的操 作方法更简洁,功能更强大,与ajax操作相关的jquery方法有如下几种,但开发中 经常使用的有三种。

1) .get(url,[data],[callback],[type])2 . g e t ( u r l , [ d a t a ] , [ c a l l b a c k ] , [ t y p e ] ) 2 ) .post(url, [data], [callback], [type])

其中:
url:代表请求的服务器端地址
data:代表请求服务器端的数据(可以是key=value形式也可以是json格式)
callback:表示服务器端成功响应所触发的函数(只有正常成功返回才执行)
type:表示服务器端返回的数据类型(jquery会根据指定的类型自动类型转换)
常用的返回类型:text、json、html等

3)$.ajax( { option1:value1,option2:value2… } ); —- 以后在掌握
常用的option有如下:
async:是否异步,默认是true代表异步
data:发送到服务器的参数,建议使用json格式
dataType:服务器端返回的数据类型,常用text和json
success:成功响应执行的函数,对应的类型是function类型
type:请求方式,POST/GET
url:请求服务器端地址

ajaxServlet2.java

package cn.ctgu.ajax;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ajaxServlet
 */
@WebServlet("/ajaxServlet2")
public class ajaxServlet2 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        /*try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
        String name=request.getParameter("name");
        String age=request.getParameter("age");


    //  response.getWriter().write("success");//返回的是一个字符串,与"text"格式对应
        //java代码只能返回一个json格式的字符串,因为java中没有json格式,然而又不能将""号改成''号(json不认识),所以只能转义
        response.getWriter().write("{\"name\":\"Tom\",\"age\":21}");
        /*//当响应消息包含中文的时候,需要设置浏览器的编码格式,否则服务端收到的数据会乱码
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("{\"name\":\"汤姆\",\"age\":21}");*/
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="../JQ/jquery-1.8.3.js"></script>
<script>
    function fn1(){
        //get异步访问
        $.get(
            "../../ajaxServlet2",//发送到url的地址
            {"name":"zhangsan","age":25},//请求参数
            function(data){//执行成功后的回调函数,里面的data可以使任意参数,即data也可以换成da,它是用来接收服务端的响应数据的
                //alert(data);
            // {\"name\":\"Tom\",\"age\":21}
                alert(data.name);
            },
        //  "text"//表示data的类型,当它换成"Json"则不会显示,因为服务端返回的是一个字符串,不是Json格式的,所以不会有任何显示解析不了
            "json"//返回的还是字符串,只不过是个json格式的字符串,当我们要求以json格式进行解析,它可以被解析出来
        );
    }
    /*
    get和post提交的区别主要体现在编码解码的过程:
    当我们请求参数中包含中文,如{"name":"张三","age":25}的时候,采用get方式提交它不会进行解码,所以提交给服务端的是个乱码,我们得手动在
    服务端添加一句 request.setCharacterEncongding("utf-8")

    而post方法则不需要,它不会乱码,当我们在服务端添加一句 request.setCharacterEncongding("utf-8")
    时反而导致乱码
    */
    function fn2(){
        //post异步访问
        $.post(
            "../../ajaxServlet2",//发送到url的地址
            {"name":"zhangsan","age":25},//请求参数
            function(data){//执行成功后的回调函数,里面的data可以使任意参数,即data也可以换成da,它是用来接收服务端的响应数据的
                //alert(data);
            // {\"name\":\"Tom\",\"age\":21}
                alert(data.name);
            },
        //  "text"//表示data的类型,当它换成"Json"则不会显示,因为服务端返回的是一个字符串,不是Json格式的,所以不会有任何显示解析不了
            "json"//返回的还是字符串,只不过是个json格式的字符串,当我们要求以json格式进行解析,它可以被解析出来
        );
    }
    function fn3(){
        $.ajax({
            url:"../../ajaxServlet2",//访问的url地址
            async:true,//是否异步
            type:"POST",//提交方式
            data:{"name":"lucy","age":18},//请求参数
            success:function(data){
                alert(data.name);
            },//请求成功的回调函数
            error:function(){
                alert("请求失败");
            },//请求失败的执行函数
            dataType:"json"//响应回来的参数解析格式
        });
    }
</script>
<body>
    <input type="button" value="get访问服务器端" onclick="fn1()"><span id="span1"></span>
    <br>
    <input type="button" value="post访问服务器端" onclick="fn2()"><span id="span2"></span>
    <br>
    <input type="button" value="ajax访问服务器端" onclick="fn3()"><span id="span2"></span>
    <br>
</body>
</html>

4、案例———Ajax校验登陆表单

database.properties

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybase
username=root
password=123456

JDBCUtilsConfig.java

package cn.ctgu.dao;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/*
 * 编写JDBC的工具类,获取数据库的连接对象采用
 * 采用读取配置文件的方式
 * 读取文件获取连接,执行一次,采用static代码块,
 * 
 * */
public class JDBCUtilsConfig {
    private static Connection con;
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;
    static {
        try {
        readConfig();
        Class.forName(driverClass);
        con=DriverManager.getConnection(url, username, password);
        }catch(Exception e) {
            throw new RuntimeException("数据库连接失败");
        }
    }
    private static void readConfig() throws Exception{
        InputStream in=JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("database.properties");
        Properties pro=new Properties();
        pro.load(in);
        driverClass=pro.getProperty("driverClass");
        url=pro.getProperty("url");
        username=pro.getProperty("username");
        password=pro.getProperty("password");
    }
    public static Connection getConnection() {
        return con;
    }
}

UserDao.java

package cn.ctgu.dao;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

public class UserDao {

    public Long CheckUsername(String username) throws SQLException {
        // TODO Auto-generated method stub
        Connection conn=JDBCUtilsConfig.getConnection();
        QueryRunner runner=new QueryRunner();
        String sql="select count(*) from user where username=?";
        Long query=(Long) runner.query(conn, sql, username,new ScalarHandler());
        return query;
    }

}

UserService.java

package cn.ctgu.service;

import java.sql.SQLException;

import cn.ctgu.dao.UserDao;

public class UserService {

    public boolean CheckUsername(String username) throws SQLException {

        UserDao dao=new UserDao();
        Long isExist=dao.CheckUsername(username);
        return isExist>0?true:false;
    }
}

CheckUsernameServlet.java

package cn.ctgu.ajax;

import java.io.IOException;
import java.sql.SQLException;

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 cn.ctgu.service.UserService;

/**
 * Servlet implementation class CheckUsernameServlet
 */
@WebServlet("/CheckUsernameServlet")
public class CheckUsernameServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得要校验的用户名
        String username=request.getParameter("username");
        //传递username到service
        UserService service=new UserService();
        boolean isExist=false;
        try {
            isExist=service.CheckUsername(username);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        response.getWriter().write("{\"isExist\":"+isExist+"}");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head></head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>会员注册</title>
<link rel="stylesheet" href="../css/bootstrap.min.css" type="text/css" />
<script src="../JQ/jquery-1.8.3.js"  type="text/javascript"></script>
<script src="../JQ/jquery.validate.min.js" type="text/javascript"></script>
<!-- 引入自定义css文件 style.css -->
<link rel="stylesheet" href="../css/style.css" type="text/css" />

<style>
body {
    margin-top: 20px;
    margin: 0 auto;
}

.carousel-inner .item img {
    width: 100%;
    height: 300px;
}

font {
    color: #3164af;
    font-size: 18px;
    font-weight: normal;
    padding: 0 10px;
}
</style>

<!-- ajax校验表单 -->
<script type="text/javascript">
    $(function(){
        //为输入框绑定事件
        $("#username").blur(function(){
            //1、失去焦点获得输入框的内容
            var usernameInput=$(this).val();
            //2、去服务端校验该用户名是否存在----ajax
            $.post(
                "${pageContext.request.contextPath}/CheckUsernameServlet",
                {"username":usernameInput},
                function(data){
                    var isExist=data.isExist;
                    //3、根据返回的isExist动态的显示信息
                    var usernameInfo="";
                    if(isExist){
                        //该用户存在
                        usernameInfo="该用户已经存在";
                        $("#usernameInfo").css("color","red");
                    }else{
                        usernameInfo="该用户可以使用";
                        $("#usernameInfo").css("color","green");
                    }
                    $("#usernameInfo").html(usernameInfo);
                },
                "json"
            );

        });
    });
</script>

</head>
<body>

    <!-- 引入header.jsp -->
    <jsp:include page="../jsp/header.jsp"></jsp:include>

    <div class="container"
        style="width: 100%; background: url('image/regist_bg.jpg');">
        <div class="row">
            <div class="col-md-2"></div>
            <div class="col-md-8"
                style="background: #fff; padding: 40px 80px; margin: 30px; border: 7px solid #ccc;">
                <font>会员注册</font>USER REGISTER
                <form class="form-horizontal" style="margin-top: 5px;">
                    <div class="form-group">
                        <label for="username" class="col-sm-2 control-label">用户名</label>
                        <div class="col-sm-6">
                            <input type="text" class="form-control" id="username"
                                placeholder="请输入用户名">
                            <span id="usernameInfo"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
                        <div class="col-sm-6">
                            <input type="password" class="form-control" id="inputPassword3"
                                placeholder="请输入密码">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="confirmpwd" class="col-sm-2 control-label">确认密码</label>
                        <div class="col-sm-6">
                            <input type="password" class="form-control" id="confirmpwd"
                                placeholder="请输入确认密码">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
                        <div class="col-sm-6">
                            <input type="email" class="form-control" id="inputEmail3"
                                placeholder="Email">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="usercaption" class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-6">
                            <input type="text" class="form-control" id="usercaption"
                                placeholder="请输入姓名">
                        </div>
                    </div>
                    <div class="form-group opt">
                        <label for="inlineRadio1" class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-6">
                            <label class="radio-inline"> <input type="radio"
                                name="inlineRadioOptions" id="inlineRadio1" value="option1"></label> <label class="radio-inline"> <input type="radio"
                                name="inlineRadioOptions" id="inlineRadio2" value="option2"></label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="date" class="col-sm-2 control-label">出生日期</label>
                        <div class="col-sm-6">
                            <input type="date" class="form-control">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="date" class="col-sm-2 control-label">验证码</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control">

                        </div>
                        <div class="col-sm-2">
                            <img src="./image/captcha.jhtml" />
                        </div>

                    </div>

                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <input type="submit" width="100" value="注册" name="submit"
                                style="background: url('./images/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0); height: 35px; width: 100px; color: white;">
                        </div>
                    </div>
                </form>
            </div>

            <div class="col-md-2"></div>

        </div>
    </div>

    <!-- 引入footer.jsp -->
    <jsp:include page="../jsp/footer.jsp"></jsp:include>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值