JSP怎么实现用户登录连接数据库的功能

本篇内容介绍了“JSP怎么实现用户登录连接数据库的功能”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

目录
  • 关于JSP用户登录连接数据库详情

    • 1、首先创建po类

    • 2、创建底层UserDao

    • 3、创建UserService(一般都会调用UserDao)

    • 4、写web层UserSrevlet

      • 4.1 重写方法 

      • 4.2创建vo层并在里面创建ResultInfo类用于封装返回数据

    • 5、开始从Dao开始写

      • 6、开始写service层

        • 7、编写最后的Servelt层

          • 7.1 用户登陆

        • 8、示例

        关于JSP用户登录连接数据库详情

        JSP怎么实现用户登录连接数据库的功能

        JSP怎么实现用户登录连接数据库的功能

        1、首先创建po类

        与数据库一一对应

        JSP怎么实现用户登录连接数据库的功能

        lombok生成get set方法

        package com.ftzlover.demo.po;
        import lombok.Getter;
        import lombok.Setter;
        @Getter
        @Setter
        public class User {
        
            private Integer userId; // 用户ID
            private String uname; // 用户名称
            private String upwd; // 用户密码
            private String nick; // 用户昵称
            private String head; // 用户头像
            private String mood; // 用户签名
        }

        2、创建底层UserDao

        JSP怎么实现用户登录连接数据库的功能

        这里就是所有创建好的层

        3、创建UserService(一般都会调用UserDao)

         private UserDao userDao = new UserDao();

        4、写web层UserSrevlet

        注意:

        1. 首先需要写@WebServlet("/user")在顶端,

        2. 接下来让其调用service层private UserService userService = new UserService();

        3. 然后让后让这个类继承 HttpServlet

        public class UserServlet extends HttpServlet {

        4.1 重写方法 
        @Override
            protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        4.2创建vo层并在里面创建ResultInfo类用于封装返回数据

        创建状态码code 提示信息 返回对象

        @Getter
        @Setter
        public class ResultInfo<T> {
        
            private Integer code; // 状态码 成功=1,失败=0
            private String msg; // 提示信息
            private T result; // 返回的对象(字符串、JavaBean、集合、Map等)
        
        }

        5、开始从Dao开始写

        Dao层:(数据访问层:数据库中的增删改查操作)通过用户名查询用户对象, 返回用户对象

        获取数据库连接

        1. 定义sql语句

        2. 预编译

        3. 设置参数

        4.  执行查询,返回结果集

        5. 判断并分析结果集

        6. 关闭资源

        package com.ftzlover.demo.dao;
        
        import com.ftzlover.demo.po.User;
        import com.ftzlover.demo.util.DBUtil;
        
        import java.sql.Connection;
        import java.sql.PreparedStatement;
        import java.sql.ResultSet;
        
        /**
         *  Dao层:(数据访问层:数据库中的增删改查操作)
         *         通过用户名查询用户对象, 返回用户对象
         *             1. 获取数据库连接
         *             2. 定义sql语句
         *             3. 预编译
         *             4. 设置参数
         *             5. 执行查询,返回结果集
         *             6. 判断并分析结果集
         *             7. 关闭资源
         */
        public class UserDao {
        
            public User queryUserByName(String userName){
                //首先创建对象
                User user = null;
                Connection connection = null;
                PreparedStatement preparedStatement = null;  //预编译对象
                ResultSet resultSet = null;
        
                try {
                    // 1. 获取数据库连接
                    connection = DBUtil.getConnetion();
                    // 2. 定义sql语句
                    String sql = "select * from tb_user where uname = ?";
                    // 3. 预编译
                    preparedStatement = connection.prepareStatement(sql);
                    // 4. 设置参数
                    preparedStatement.setString(1, userName);
                    // 5. 执行查询,返回结果集
                    resultSet = preparedStatement.executeQuery();
                    // 6. 判断并分析结果集
                    if (resultSet.next()) {
                        user = new User();
                        user.setUserId(resultSet.getInt("userId"));
                        user.setUname(userName);
                        user.setHead(resultSet.getString("head"));
                        user.setMood(resultSet.getString("mood"));
                        user.setNick(resultSet.getString("nick"));
                        user.setUpwd(resultSet.getString("upwd"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 7. 关闭资源
                    DBUtil.close(resultSet,preparedStatement,connection);
                }
        
        
                return  user;
            }
        }

        6、开始写service层

        package com.ftzlover.demo.service;
        
        import cn.hutool.core.util.StrUtil;
        import cn.hutool.crypto.digest.DigestUtil;
        import com.ftzlover.demo.dao.UserDao;
        import com.ftzlover.demo.po.User;
        import com.ftzlover.demo.vo.ResultInfo;
        /*Service层:(业务逻辑层:参数判断、业务逻辑处理)
                1. 判断参数是否为空
                如果为空
                设置ResultInfo对象的状态码和提示信息
                返回resultInfo对象
                2. 如果不为空,通过用户名查询用户对象
                3. 判断用户对象是否为空
                如果为空
                设置ResultInfo对象的状态码和提示信息
                返回resultInfo对象
                4. 如果用户对象不为空,将数据库中查询到的用户对象的密码与前台传递的密码作比较 (将密码加密后再比较)
                如果密码不正确
                设置ResultInfo对象的状态码和提示信息
                返回resultInfo对象
                5. 如果密码正确
                设置ResultInfo对象的状态码和提示信息
                6. 返回resultInfo对象
        
         */
        public class UserService {
            private UserDao userDao = new UserDao();
        
            public ResultInfo<User> userLogin(String userName,String userPwd){
                ResultInfo<User> resultInfo = new ResultInfo<>();
        
                // 数据回显:当登录实现时,将登录信息返回给页面显示
                User u = new User();
                u.setUname(userName);
                u.setUpwd(userPwd);
                // 设置到resultInfo对象中
                resultInfo.setResult(u);
        
                //  1. 判断参数是否为空
                if (StrUtil.isBlank(userName) || StrUtil.isBlank(userPwd)) {
                    // 如果为空 设置ResultInfo对象的状态码和提示信息
                    resultInfo.setCode(0);
                    resultInfo.setMsg("用户姓名或密码不能为空!");
                    // 返回resultInfo对象
                    return resultInfo;
        
                }
        
                // 2. 如果不为空,通过用户名查询用户对象
                User user = userDao.queryUserByName(userName);
        
        
                // 3. 判断用户对象是否为空
                if (user == null) {
                    // 如果为空,设置ResultInfo对象的状态码和提示信息
                    resultInfo.setCode(0);
                    resultInfo.setMsg("该用户不存在!");
                    // 返回resultInfo对象
                    return resultInfo;
                }
        
                //  4. 如果用户对象不为空,将数据库中查询到的用户对象的密码与前台传递的密码作比较 (将密码加密后再比较)
                // 将前台传递的密码按照MD5算法的方式加密
                userPwd = DigestUtil.md5Hex(userPwd);
        
                // 判断加密后的密码是否与数据库中的一致
                if (!userPwd.equals(user.getUpwd())) {
                    // 如果密码不正确
                    resultInfo.setCode(0);
                    resultInfo.setMsg("用户密码不正确!");
                    return resultInfo;
                }
                resultInfo.setCode(1);
                resultInfo.setResult(user);
                return resultInfo;
            }
        }

        7、编写最后的Servelt层

        7.1 用户登陆
        package com.ftzlover.demo.web;
        
        import com.ftzlover.demo.po.User;
        import com.ftzlover.demo.service.UserService;
        import com.ftzlover.demo.vo.ResultInfo;
        
        import javax.servlet.ServletException;
        import javax.servlet.annotation.WebServlet;
        import javax.servlet.http.Cookie;
        import javax.servlet.http.HttpServlet;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import java.io.IOException;
        @WebServlet("/user")
        public class UserServlet extends HttpServlet {
        
            private UserService userService = new UserService();
        
            @Override
            protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        
                // 接收用户行为
                String actionName = request.getParameter("actionName");
                if ("login".equals(actionName)) {
        
                    // 用户登录
                    userLogin(request, response);
        
                }
        
        
            }
            /**
             * 用户登录
             1. 获取参数 (姓名、密码)
             2. 调用Service层的方法,返回ResultInfo对象
             3. 判断是否登录成功
             如果失败
                将resultInfo对象设置到request作用域中
                请求转发跳转到登录页面
             如果成功
                将用户信息设置到session作用域中
                   判断用户是否选择记住密码(rem的值是1)
                      如果是,将用户姓名与密码存到cookie中,设置失效时间,并响应给客户端
                      如果否,清空原有的cookie对象
             重定向跳转到index页面
             * @param request
             * @param response
             */
        
            private void userLogin(HttpServletRequest request, HttpServletResponse response) {
                // 1. 获取参数 (姓名、密码)
                String userName = request.getParameter("userName");
                String userPwd = request.getParameter("userPwd");
        
                // 2. 调用Service层的方法,返回ResultInfo对象
                ResultInfo<User> resultInfo = userService.userLogin(userName, userPwd);
        
                // 3. 判断是否登录成功
                if (resultInfo.getCode() == 1) { // 如果成功
                    //  将用户信息设置到session作用域中
                    request.getSession().setAttribute("user", resultInfo.getResult());
                    //  判断用户是否选择记住密码(rem的值是1)
                    String rem = request.getParameter("rem");
                    // 如果是,将用户姓名与密码存到cookie中,设置失效时间,并响应给客户端
                    if ("1".equals(rem)) {
                        // 得到Cookie对象
                        Cookie cookie = new Cookie("user",userName +"-"+userPwd);
                        // 设置失效时间
                        cookie.setMaxAge(3*24*60*60);
                        // 响应给客户端
                        response.addCookie(cookie);
                    } else {
                        // 如果否,清空原有的cookie对象
                        Cookie cookie = new Cookie("user", null);
                        // 删除cookie,设置maxage为0
                        cookie.setMaxAge(0);
                        // 响应给客户端
                        response.addCookie(cookie);
                    }
                    // 重定向跳转到index页面
                    try {
                        response.sendRedirect("index.html");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
        
                } else { // 失败
                    // 将resultInfo对象设置到request作用域中
                    request.setAttribute("resultInfo", resultInfo);
                    // 请求转发跳转到登录页面
                    try {
                        request.getRequestDispatcher("login.jsp").forward(request, response);
                    } catch (ServletException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
        
            }
        
        
        }

        附件:util层的DBUtil

        package com.ftzlover.demo.util;
        
        import java.io.InputStream;
        import java.sql.*;
        import java.util.Properties;
        
        
        public class DBUtil {
        
            // 得到配置文件对象
            private static Properties properties = new Properties();
        
            static {
                try {
                    // 加载配置文件(输入流)
                    InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
                    System.out.println("是否获取到流对象:" + in);
                    System.out.println("流对象:" + properties);
                    // 通过load()方法将输入流的内容加载到配置文件对象中
                    properties.load(in);
                    // 通过配置文件对象的getProperty()方法获取驱动名,并加载驱动
                    Class.forName(properties.getProperty("jdbcName"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        
        
            public static Connection getConnetion() {
                Connection connection = null;
                try {
                    // 得到数据库连接的相关信息
                    String dbUrl = properties.getProperty("dbUrl");
                    System.out.println(dbUrl);
                    String dbName = properties.getProperty("dbName");
                    System.out.println(dbName);
                    String dbPwd = properties.getProperty("dbPwd");
                    System.out.println(dbName);
                    // 得到数据库连接
                    connection = DriverManager.getConnection(dbUrl, dbName, dbPwd);
                    System.out.println(connection);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
        
                return connection;
            }
        
        
            public static void close(ResultSet resultSet,
                                     PreparedStatement preparedStatement,
                                     Connection connection) {
        
                try {
                    // 判断资源对象如果不为空,则关闭
                    if (resultSet != null) {
                        resultSet.close();
                    }
                    if (preparedStatement != null) {
                        preparedStatement.close();
                    }
                    if (connection != null) {
                        connection.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
        
            }
        
        }

        8、示例

        JSP怎么实现用户登录连接数据库的功能

        JSP怎么实现用户登录连接数据库的功能

        十分炫酷的登陆界面加完善的后台登陆界面截图:

        JSP怎么实现用户登录连接数据库的功能

        JSP怎么实现用户登录连接数据库的功能

        JSP怎么实现用户登录连接数据库的功能

        数据库代码:新建数据库名叫my 建表名叫tb_user

        CREATE TABLE `tb_user` (
          `userId` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键,自动增长',
          `uname` varchar(50) NOT NULL COMMENT '用户名',
          `upwd` varchar(50) DEFAULT NULL COMMENT '密码',
          `nick` varchar(50) DEFAULT NULL COMMENT '昵称',
          `head` varchar(100) DEFAULT NULL COMMENT '头像',
          `mood` varchar(500) DEFAULT NULL COMMENT '心情',
          PRIMARY KEY (`userId`)
        ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

        “JSP怎么实现用户登录连接数据库的功能”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!