AJAX 与Axios

一、案例准备

1、首先数据库不可

-- auto-generated definition

create table users
(
    id       varchar(50)   not null
        primary key,
    name     varchar(50)   not null comment '姓名',
    age      int           null comment '年龄',
    sex      int default 1 null comment '性别,1代表男,0代表默认男,',
    password varchar(20)   not null,
    check (`sex` in (0, 1))
)
    charset = utf8;


2、实体类紧跟其后

public class User {

    private String id;
    private String name;
    private String password;
    private int age;
    private int sex;
}
//此处省略gettersetter方法以及构造等其他方法

3、然后就是数据库访问

public class JdbcUtils {

    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&charsetEncoding=utf-8";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";
    private static Connection con = null;
    private static Statement stm = null;
    private static ResultSet rs = null;

    /**
     * @return
     * 获取连接
     */
    public static Connection getCon() {
        try {
//            1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
//            2.加载连接
            con = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }


    /**
     * @param sql
     * @return
     * 公共增删改的方法,因为增删改对行影响,所以返回row
     */

    public static int update(String sql) {
        int row = 0;
        try {
            if (con == null) {
                con = getCon();
            }
            stm = con.createStatement();
            row = stm.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }


    /**
     * @param sql
     * @return
     * 查询方法
     */
    public static ResultSet query(String sql) {
        try {
            if (con == null) {
                con = getCon();
            }
            stm = con.createStatement();
            rs = stm.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    /**
     *
     * @param connection
     * @param statement
     * @param resultSet
     * 关闭连接,释放资源
     */
    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (connection != null) {
                connection.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

public class UserDao {

    /**
     * 
     * @param sql
     * @return
     * 封装的是一个集体查数据私有方法
     */
    private List<User> get(String sql) {
        ResultSet resultSet = JdbcUtils.query(sql);

        List<User> list = new ArrayList<>();
        User user;
        try {
            while (resultSet.next()) {
                user = new User();
                user.setId(resultSet.getString("id"));
                user.setName(resultSet.getString("name"));
                user.setAge(resultSet.getInt("age"));
                user.setSex(resultSet.getInt("sex"));
                user.setPassword(resultSet.getString("password"));
                list.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeAll(null, null, resultSet);
        }
        return list;
    }

    /**
     * 
     * @param username 用户名
     * @param password 密码
     * @return
     * 登录方法简单实现一下,
     */
    public boolean login(String username, String password) {
        String sql = "SELECT * FROM users WHERE name='" + username + "' AND password='" + password + "'";
        List<User> list = get(sql);
        if (list == null || list.isEmpty()) {
            return false;
        }
        System.out.println(list);
        return true;
    }
}

4、直接servlet

@WebServlet(urlPatterns = "/user")
public class UserController extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        System.out.println(username + "---doGet---" + password);

        UserDao userDao = new UserDao();
        boolean login = userDao.login(username, password);
        System.out.println(login);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      /*
      //        字节流,中文乱码
        ServletInputStream inputStream = request.getInputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        String str = null;
        while ((len = inputStream.read(bytes)) != -1) {
            str = new String(bytes, 0, len);
        }
        System.out.println("str-----" + str);
//        字符流和字节流获取数据任取一种都可,不过字节流中文乱码建议使用字符流
        */

/*
//        设置编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");
*/

//        使用字符读取数据
        BufferedReader reader = request.getReader();
        char[] buf = new char[1024];
        int len = 0;
//        StringBuilder str = new StringBuilder();
        StringBuffer str = new StringBuffer();
        while ((len = reader.read(buf)) != -1) {
            str.append(buf, 0, len);
        }
        UserDao userDao = new UserDao();
//        将前端获取到的StringBuffer对象转成String
        String s = String.valueOf(str);
        System.out.println("str=====" + str+"--------ts====="+s);

//        先判空,在判断是不是JSON格式
        if (s != null) {
            if (JSONObject.isValid(s)) {
//        转换为JSON格式
                JSONObject jsonObject = JSONObject.parseObject(s);
                String username = jsonObject.getString("username");
                String password = jsonObject.getString("password");
                System.out.println(username + "---doPost---" + password);
                boolean login = userDao.login(username, password);
                System.out.println(login);
            }else {
                System.out.println("数据格式问题用户密码默认为空");
                boolean login = userDao.login(null, null);
                System.out.println(login);
            }
        }
    }

}

/* 
   @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//        字节流,中文乱码
        ServletInputStream inputStream = request.getInputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        String str = null;
        while ((len = inputStream.read(bytes)) != -1) {
            str = new String(bytes, 0, len);
        }
        System.out.println("str-----" + str);
        String[] data = str.split(",");
        for (String datum : data) {
            System.out.println(datum);
        }

    }
*/

5、过滤器

@WebFilter(urlPatterns = "/*")
public class EncodingFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String method = request.getMethod();
        System.out.println(method);

        //判断post方法,设置编码
        if ("POST".equals(method)) {
            servletRequest.setCharacterEncoding("utf-8");
            servletResponse.setContentType("text/html; charset=UTF-8");
        }
        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {

    }

}

5、注意一点

Get和post能够提交数据,那么他们什么不同呢?

二、原生ajax请求

1、原生的使用XMLHttpRequest对象获取的异步操作

//发送同步请求
        //1.创建ajax引擎对象----所有操作都是由ajax引擎完成
        var xmlHttp = new XMLHttpRequest();
        //2.为引擎对象绑定监听事件
        xmlHttp.onreadystatechange = function() {
            //当状态变化时处理的事情
            if (xmlHttp.readyState == 4 &amp;&amp; xmlHttp.status == 200) {
                //5.接收响应信息
                var data = xmlHttp.responseText;
                //alert(data);
                document.getElementById("span2").innerHTML=data;
            }
        }
        //3.绑定服务器地址
        //第一个参数:请求方式GET/POST
        //第二个参数:后台服务器地址
        //第三个参数:是否是异步 true--异步   false--同步
        xmlHttp.open("GET", "http://localhost:8099/ajax_demo/user"
            false);
        //4.发送请求
        xmlHttp.send();

        // 在JS原生Ajax中,也可以指定 如果是post提交
        // 在发送请求之前设置一个头
        // xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		//xmlHttp.send(data);

2、看原生ajax实例用法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>原生ajax(通过XMLHttpRequest对象登录</title>

    <!--
    使用原生ajax异步传输数据
    -->
</head>
<body>
<div id="loginFrom" style="margin: 20% 30%">
    <input type="text" name="username" placeholder="用户" class="params"><br>
    <input type="text" name="password" placeholder="密码" class="params"><br>
    <input type="submit" value="get登录" onclick="loginGet()">
    <input type="submit" value="post登录" onclick="loginPost()">

    <div class="result" width="10px" height="10px"></div>
</div>

<script>

    function loginGet() {

        let username = document.getElementsByName("username")[0].value;
        let password = document.getElementsByName("password")[0].value;

        //1.创建ajax引擎对象
        let xmlHttpRequest = new XMLHttpRequest();

        console.log("-------get====" + "username=" + username + ",password=" + password)
        //3.绑定服务器地址
        //第一个参数:请求方式GET/POST
        //第二个参数:后台服务器地址
        //第三个参数:是否是异步 true--异步   false--同步

        xmlHttpRequest.open("GET", "http://localhost:8099/ajax_axios_demo/user?username=" + username + "&amp;password=" + password, true);
        xmlHttpRequest.send();

        //2.为引擎对象绑定监听事件
        xmlHttpRequest.onreadystatechange = function () {
            //当状态变化时处理
            if (xmlHttpRequest.status == 200 &amp;&amp; xmlHttpRequest.readyState == 4) {
                //接收响应数据
                let data = xmlHttpRequest.responseText;
                console.log("-----" + data);
            } else {
                console.log("error!")
            }
        }
    }

    function loginPost() {

        let username = document.getElementsByName("username")[0].value;
        let password = document.getElementsByName("password")[0].value;

        //1.创建ajax引擎对象
        let xmlHttpRequest = new XMLHttpRequest();

        console.log("-------post====" + "username=" + username + ",password=" + password)

        //3.绑定服务器地址
        //第一个参数:请求方式GET/POST
        //第二个参数:后台服务器地址
        //第三个参数:是否是异步 true--异步   false--同步
        xmlHttpRequest.open("POST", "http://localhost:8099/ajax_axios_demo/user", true);
        xmlHttpRequest.setRequestHeader("Content-type", "application/json;charset=utf-8");
        //4.发送请求
        xmlHttpRequest.send("{'username':'" + username + "','password':'" + password+"'}");

        // 在JS原生Ajax中,也可以指定 如果是post提交
        // 在发送请求之前设置一个头
        //2.为引擎对象绑定监听事件
        xmlHttpRequest.onreadystatechange = function () {
            //当状态变化时处理
            if (xmlHttpRequest.status == 200 && xmlHttpRequest.readyState == 4) {
                //接收响应数据
                let data = xmlHttpRequest.responseText;
                console.log("-----" + data);
            } else {
                console.log("error!")
            }
        }
    }

    function login() {

        let username = document.getElementsByName("username")[0].value;
        let password = document.getElementsByName("password")[0].value;
        //1.创建ajax引擎对象
        let xmlHttpRequest = new XMLHttpRequest();
        //2.为引擎对象绑定监听事件
        xmlHttpRequest.onreadystatechange = function () {
            //当状态变化时处理
            if (xmlHttpRequest.status == 200 && xmlHttpRequest.readyState == 4) {
                //接收响应数据
                let data = xmlHttpRequest.responseText;
                console.log("-----" + data);
            } else {
                console.log("error!")
            }
        }

        console.log("-------====" + "username=" + username + ",password=" + password)
        xmlHttpRequest.open("GET", "http://localhost:8099/ajax_axios_demo/user?username=" + username + "&password=" + password, true);
        xmlHttpRequest.send();

        //3.绑定服务器地址
        //第一个参数:请求方式GET/POST
        //第二个参数:后台服务器地址
        //第三个参数:是否是异步 true--异步   false--同步
        // xmlHttpRequest.open("POST", "http://localhost:8099/ajax_axios_demo/user?username=admin&password=123456", true);
        // xmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        //4.发送请求
        // xmlHttpRequest.send();

        // 在JS原生Ajax中,也可以指定 如果是post提交
        // 在发送请求之前设置一个头
    }
</script>

</body>
</html>

三、AJAX

1、先导入jQuery.js

<script src="https://unpkg.com/axios/dist/jQuery.min.js"></script>

2、看jQuery封装的ajax在实例用法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>基于jQuery的ajax登录</title>
    <!--
        使用jQuery.js封装的ajax
        -->
</head>
<body>
<div id="loginFrom" style="margin: 20% 30%">
    <input type="text" name="username" placeholder="用户" class="params"><br>
    <input type="text" name="password" placeholder="密码" class="params"><br>
    <input type="submit" value="get登录" onclick="loginGet()">
    <input type="submit" value="post登录" onclick="loginPost()">

    <div class="result" width="10px" height="10px"></div>

    <script src="static/jquery-3.6.0.min.js"></script>

    <script>

        function loginGet() {
            let username = document.getElementsByName("username")[0].value;
            let password = document.getElementsByName("password")[0].value;
            console.log("-------get--------")
            $.ajax({
                method: 'GET',
                // url:'http://localhost:8099/ajax_demo/user?username='+username+'&password='+password,
                url: 'http://localhost:8099/ajax_demo/user',
                data: {
                    username: username,
                    password: password
                }
            }).then(response => {
                console.log(response.data)
            }).catch(error => {
                console.log(error.data);
            });

        };

        function loginPost() {

            let username = document.getElementsByName("username")[0].value;
            let password = document.getElementsByName("password")[0].value;
            console.log("-------post--------");
            $.ajax({
                method: 'POST',
                url: 'http://localhost:8099/ajax_demo/user',
                data: {
                    username: username,
                    password: password
                }
            }).then(response => {
                console.log(response.data);
            }).catch(error => {
                console.log(error.data);
            });
        }

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

四、Axios

1、先导入axios.js

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


//由于发送的是json字符串,get携带数据使用常规方法接受可以,但post不携带数据,故需用键值对接

2、看axios在实例中用法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>基于axios登录</title>

    <!--
        使用axios发送异步请求
        -->

</head>
<body>
<div id="loginFrom" style="margin: 20% 30%">
    <input type="text" name="username" placeholder="用户" class="params"><br>
    <input type="text" name="password" placeholder="密码" class="params"><br>
    <input type="submit" value="get登录" onclick="loginGet()">
    <input type="submit" value="post登录" onclick="loginPost()">

    <div class="result" width="10px" height="10px"></div>
</div>


<script src="static/axios.js"></script>

<script>

    function loginGet() {
        let username = document.getElementsByName("username")[0].value;
        let password = document.getElementsByName("password")[0].value;
        console.log("-------get--------")
        axios.get('http://localhost:8099/ajax_axios_demo/user',
            {
                params: {
                    username: username,
                    password: password
                },
            }).then(response => {
            console.log(response.data)
        }).catch(error => {
            console.log(error.data);
        });
    }

    function loginPost() {

        let username = document.getElementsByName("username")[0].value;
        let password = document.getElementsByName("password")[0].value;
        console.log("-------post--------");
        axios({
            method: 'post',
            // url:'/user',
            url: 'http://localhost:8099/ajax_axios_demo/user',
            data: {
                username: username,
                password: password
            }
        }).then(response => {
            console.log(response.data);
        }).catch(error => {
            console.log(error.data);
        });
    }

</script>

</body>
</html>

3、基于Vue的axios

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>基于Vue的axios登录</title>
    <!--
        基于Vue的axios异步请求
        -->
        <script src="static/vue-2.6.14.js"></script>
<!--    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>-->


</head>
<body>
<div id="app">
    <div id="loginFrom" style="margin: 20% 30%">
        <input v type="text" placeholder="用户" v-model="username"><br>
        <input type="text" placeholder="密码" v-model="password"><br>
        <input type="submit" value="get登录" @click="loginGet">
        <input type="submit" value="post登录" @click="loginPost">

    </div>
</div>

<script src="static/axios.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            username: '',
            password: ''
        },
        methods: {
            loginGet() {
                console.log("-------get--------")
                axios.get('http://localhost:8099/ajax_axios_demo/user',
                    {
                        params: {
                            username: this.username,
                            password: this.password
                        },
                    }).then(response => {
                    console.log(response.data)
                }).catch(error => {
                    console.log(error.data);
                });
            },
            loginPost() {
                console.log("-------post--------");
                axios({
                    method: 'post',
                    url: 'http://localhost:8099/ajax_axios_demo/user',
                    data: {
                        username: this.username,
                        password: this.password
                    }
                }).then(response => {
                    console.log(response.data);
                }).catch(error => {
                    console.log(error.data);
                });
            }
        }
    });

</script>
</body>
</html>

原文地址:https://blog.csdn.net/hsp262323/article/details/124280529

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_41456.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注