服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Ajax登录验证实现代码

Ajax登录验证实现代码

2021-10-06 10:58wbcra Java教程

这篇文章主要为大家详细介绍了jQuery+ajax实现用户登录验证,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package cn.hp.util;
import java.sql.*;
public class JDBCUtils {
    static Connection connection = null ;
    static Statement statement = null ;
    static PreparedStatement preparedStatement = null ;
    static ResultSet resultSet = null ;
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_system?characterEncoding=utf8&serverTimezone=UTC", "root", "root");
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
//    新增和修改  DML 操作 String sql , sql中的参数    preparedStatement   Object[] arr 用来补全sql中的?
    public static int DML(String sql , Object[] arr  ){  // 可变参数 Object ... arr  0~n个参数
        int update = 0 ;
        try{
            preparedStatement = connection.prepareStatement(sql);
//            循环完毕,会将sql中全部? 补充齐
            for (int i = 0 ; i < arr.length ; i++){
                preparedStatement.setObject(i+1 , arr[i] );
            }
            update = preparedStatement.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }
        return update ;
    }
    //     带参查询  DQL 操作
    public static ResultSet DQL(String sql , Object[] arr ){
        try{
            preparedStatement = connection.prepareStatement(sql);
//            循环完毕,会将sql中全部? 补充齐
            for (int i = 0 ; i < arr.length ; i++){
                preparedStatement.setObject(i+1 , arr[i] );
            }
            resultSet = preparedStatement.executeQuery();
        }catch (SQLException e){
            e.printStackTrace();
        }
        return resultSet ;
    }
    //    单独提供关闭资源方法
    public static void close(){
        try {
            if (statement!=null){
                statement.close();
            }
            if (connection!= null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package cn.hp.service;
import cn.hp.dao.UserDao;
public class UserService {
    public boolean login(String account, String password) {
        //service层,依赖于dao层 制定某一条sql执行
        UserDao userDao = new UserDao();
        int select = userDao.selectByAccountAndPassword(account ,password);
        if (select>0){
          return true;
        }else {
            return false;
        }
    }
    public boolean check(String account) {
        //service层,依赖于dao层 制定某一条sql执行
        UserDao userDao = new UserDao();
        int select = userDao.selectByAccount(account);
        if (select>0){
            return true;
        }else {
            return false;
        }
    }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package cn.hp.servlet;
import cn.hp.service.UserService;
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("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置用户输入的编码格式,因为有可能是中文
        req.setCharacterEncoding("utf-8");
        //2.获取用户数输入的内容
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        //3.依据service来判断当前登录的账号密码是否正确
        //User表 定义一个UserService 用来处理 所有和user有关的业务
        UserService userService = new UserService();
        //login方法传入账号密码  返回是否登录成功
        boolean flag = userService.login(account,password);
        //4.依据是否登录成功,进行控制页面的跳转
        if (flag){
            req.getRequestDispatcher("success.jsp").forward(req,resp);
        }else {
            req.setAttribute("msg","密码错误,请重新登录!");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package cn.hp.servlet;
import cn.hp.service.UserService;
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("/check")
public class CheckServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置用户输入的编码格式,因为有可能是中文
        req.setCharacterEncoding("utf-8");
        //2.获取用户数输入的内容
        String account = req.getParameter("account");
        //3.依据service来判断当前登录的账号密码是否正确
        //User表 定义一个UserService 用来处理 所有和user有关的业务
        UserService userService = new UserService();
        //使用check方法  检出是否存在用户  true 存在用户  false 不存在
        boolean flag = userService.check(account);
        resp.getWriter().println(flag);
    }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package cn.hp.dao;
import cn.hp.util.JDBCUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao {
    public int selectByAccountAndPassword(String account, String password) {
        //执行select查询sql语句
        String sql = "select count(*) from user where account = ? and password = ?";
        Object[] objects = {account , password};
        ResultSet resultSet = JDBCUtils.DQL(sql,objects);
        int select = 0;
        try {
            while (resultSet.next()){
                select = resultSet.getInt(1);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return select;
    }
    public int selectByAccount(String account) {
        //执行select查询sql语句
        String sql = "select count(*) from user where account = ? ";
        Object[] objects = {account };
        ResultSet resultSet = JDBCUtils.DQL(sql,objects);
        int select = 0;
        try {
            while (resultSet.next()){
                select = resultSet.getInt(1);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return select;
    }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录页</title>
    <script src="js/jquery-3.6.0.js"></script>
</head>
<body>
    <form action="login">
        账号:<input id="input1" type="text" name="account" /> <span id="span1"></span> <br/>
        密码:<input type="password" name="password" /> <span style="color:red"> ${msg } </span><br/>
        <input type="submit" value="登录"/>
    </form>
</body>
<script>
    // 使用jQuery完成ajax校验 ,当前账号是否存在
    $("#input1").blur(function () {
        //    发送ajax请求,获取到当前输入的账号是否存在,写入到span1标签中
        let account = $("#input1").val();
        $.ajax({
            url:"check",
            // data:{"account":$("#input1").val() },
            data:"account="+account ,
            type:"get",
            success:function (data) {
                let data1 = JSON.parse(data);
                if (data1){
                    // 表示存在当前账号
                    // 可以登录
                    $("#span1").html("可以登录");
                    $("#span1").attr("style","color:green");
                }else {
                    $("#span1").html("未注册");
                    $("#span1").attr("style","color:red");
                }
            }
        })
    })
</script>
</html>

原文链接:https://blog.csdn.net/wbcra/article/details/118014948

延伸 · 阅读

精彩推荐