servlet+jdbc+jsp实现登录界面的验证(基于MVC思想)

发布时间:2024年01月06日

一、MVC的概念

MVC是模型(Model)和视图(View)以及控制器(Controller)的简写,是一种将数据、界面显示和业务 逻辑进行分离的组织方式,这样在改进界面及用户交互时,不需要重新编写业务逻辑,从而提高了 代码的可维护性。

  • M:主要用于封装业务数据的JavaBean(Bean) 和 业务逻辑的JavaBean(Service)及访问数据库的

DAO对象。

  • V:主要负责数据收集 和 数据展现,通常由JSP文件完成。

  • C:主要负责流程控制 和 页面跳转,通常由Servlet完成。

在这里插入图片描述

原始的登录验证方法:

在这里插入图片描述

改进的登录验证方法:

在这里插入图片描述

这样实现了解耦,从而具备了更好的扩展性。

二、需求

  1. 浏览器 进入 登录界面,输入用户名、密码,发送到服务器。
  2. 服务器完成数据库查询和验证,返回验证结果。
  3. 验证结果呈现在响应界面上。

三、代码演示

1、编写登录界面

  1. 创建空工程,在工程中创建javaEE模块

  2. 配置中设置tomcat的部署

    在这里插入图片描述

    在这里插入图片描述

  3. 编写login界面

    <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    <!DOCTYPE html>
    <html>
    <head>
      <title>JSP - login</title>
    </head>
    <body>
    <form action="loginServlet" method="post">
      用户名:<input type="text" name="userName"><br>
      密  码:<input type="text" name="password"><br>
      <input type="submit" value="登录">
    </form>
    </body>
    
```

2、编写LoginServlet实现获取用户名和密码

  1. 编写servlet

    • LoginServlet

      package com.example.login_demo.servlet;
      
      import com.example.login_demo.pojo.User;
      import com.example.login_demo.service.UserService;
      
      import javax.servlet.*;
      import javax.servlet.http.*;
      import javax.servlet.annotation.*;
      import java.io.IOException;
      
      @WebServlet(name = "LoginServlet", value = "/loginServlet")
      public class LoginServlet extends HttpServlet {
          @Override
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              this.doPost(request, response);
          }
      
          @Override
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              //1、获取的用户名和密码
              String userName = request.getParameter("userName");
              System.out.println("获取的用户名:" + userName);
              String password = request.getParameter("password");
              System.out.println("获取的密码:" + password);
          }
      }
      
      
  2. 单元测试:

    • 运行tomcat

    • 访问登录界面,发送登录请求

      在这里插入图片描述

3、操作数据库部分

  1. 数据准备,db_web数据库下准备t_user表

    在这里插入图片描述

  2. 编写DbUtils,实现jdbc的封装

    package com.example.login_demo.utils;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    public class DbUtils {
    
        private static String jdbcName;
        private static String dbUrl;
        private static String dbUserName;
        private static String dbPassword;
    
        static {
            jdbcName = "com.mysql.jdbc.Driver";
            dbUrl = "jdbc:mysql://localhost:3306/db_web?useSSL=false";
            dbUserName = "root";
            dbPassword = "root";
            try {
                Class.forName(jdbcName);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    
        public static Connection getConnection() throws SQLException {
            Connection connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
            return connection;
        }
    
        public static void closeResource(Connection connection, PreparedStatement preparedStatement) throws SQLException {
            if (null != connection){
                connection.close();
            }
            if (null != preparedStatement){
                preparedStatement.close();
            }
        }
    
    }
    
    
  3. 原始数据类型User

    package com.example.login_demo.pojo;
    
    public class User {
    
      private int id;
    
      private String userName;
    
      private String password;
    
      public User(String userName, String password) {
          this.userName = userName;
          this.password = password;
      }
    
      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 + '\'' +
                  '}';
      }
    }
    
    
  4. dao层直接操作数据库

    • UserDao接口

      package com.example.login_demo.dao;
      
      import com.example.login_demo.pojo.User;
      
      public interface UserDao {
      
          //查询用户
          User userLogin(User user);
      }
      
    • UserDaoImpl接口实现类

      package com.example.login_demo.dao;
      
      import com.example.login_demo.pojo.User;
      import com.example.login_demo.utils.DbUtils;
      
      import java.sql.Connection;
      import java.sql.PreparedStatement;
      import java.sql.ResultSet;
      import java.sql.SQLException;
      
      public class UserDaoImpl implements UserDao {
          @Override
          public User userLogin(User user) {
              Connection connection = null;
              PreparedStatement preparedStatement = null;
              ResultSet resultSet = null;
              try {
                  //1、获取数据库连接
                  connection = DbUtils.getConnection();
      
                  //2、准备sql语句
                  String sql = "select * from t_user where userName = ? and password = ?";
      
                  //3、执行sql返回结果
                  preparedStatement = connection.prepareStatement(sql);
                  preparedStatement.setString(1, user.getUserName());
                  preparedStatement.setString(2, user.getPassword());
                  resultSet = preparedStatement.executeQuery();
                  if (resultSet.next()){
                      User returnUser = new User(resultSet.getString("userName"), resultSet.getString("password"));
                      returnUser.setId(Integer.parseInt(resultSet.getString("id")));
                      return returnUser; //查找成功
                  }
              }catch (SQLException e){
                  e.printStackTrace();
              }finally {
                  //4、释放资源
                  try {
                      DbUtils.closeResource(connection, preparedStatement);
                      if (null != resultSet){
                          resultSet.close();
                      }
                  } catch (SQLException e) {
                      e.printStackTrace();
                  }
              }
              return null;//查找失败
          }
      
          public static void main(String[] args) {
              UserDao userDao = new UserDaoImpl();
              User admin = userDao.userLogin(new User("admin", "12345"));
              System.out.println("查找到的用户:" + admin);
          }
      }
      
      
  5. 单元测试:

    • 执行UserDaoImpl中的测试代码

      在这里插入图片描述

4、service层实现

  1. UserDaoFactory实现:简单的静态工厂实现UserDao的实例创建,实现创建和使用的解耦

    package com.example.login_demo.factory;
    
    import com.example.login_demo.dao.UserDao;
    import com.example.login_demo.dao.UserDaoImpl;
    
    public class UserDaoFactory {
    
        public static UserDao getUserDao(){
            return new UserDaoImpl();
        }
    }
    
  2. service层实现dao层调用

    package com.example.login_demo.service;
    
    import com.example.login_demo.dao.UserDao;
    import com.example.login_demo.factory.UserDaoFactory;
    import com.example.login_demo.pojo.User;
    
    public class UserService {
        private UserDao userDao;
    
        public UserService(){
            this.userDao = UserDaoFactory.getUserDao();
        }
    
        public User userLoginService(User user){
            return userDao.userLogin(user);
        }
    
    }
    
    

5、修改Servlet,实现数据库的查找验证

  1. LoginServlet

    package com.example.login_demo.servlet;
    
    import com.example.login_demo.pojo.User;
    import com.example.login_demo.service.UserService;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    
    @WebServlet(name = "LoginServlet", value = "/loginServlet")
    public class LoginServlet extends HttpServlet {
      @Override
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          this.doPost(request, response);
      }
    
      @Override
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          //1、获取的用户名和密码
          String userName = request.getParameter("userName");
          System.out.println("获取的用户名:" + userName);
          String password = request.getParameter("password");
          System.out.println("获取的密码:" + password);
          //2、创建UserService类型的对象实现数据的校验功能
          UserService userService = new UserService();
          User user = userService.userLoginService(new User(userName, password));
          if (null != user){
              System.out.println("登录成功!");
          }else {
              System.out.println("登录失败!");
          }
      }
    }
    
    
  2. 单元测试:

    在这里插入图片描述

6、修改Servlet,实现页面的跳转

  1. 修改LoginServlet,当成功时,跳转到成功界面;当失败时,跳转回登录界面并显示账号或者密码错误

    package com.example.login_demo.servlet;
    
    import com.example.login_demo.pojo.User;
    import com.example.login_demo.service.UserService;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    
    @WebServlet(name = "LoginServlet", value = "/loginServlet")
    public class LoginServlet extends HttpServlet {
      @Override
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          this.doPost(request, response);
      }
    
      @Override
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          //1、获取的用户名和密码
          String userName = request.getParameter("userName");
          System.out.println("获取的用户名:" + userName);
          String password = request.getParameter("password");
          System.out.println("获取的密码:" + password);
          //2、创建UserService类型的对象实现数据的校验功能
          UserService userService = new UserService();
          User user = userService.userLoginService(new User(userName, password));
          if (null != user){
              System.out.println("登录成功!");
              //登录成功的信息放入session对象实现多个请求共享
              request.getSession().setAttribute("user", user);
              //实现客户端跳转
              response.sendRedirect("main.jsp");
    
          }else {
              System.out.println("登录失败,用户名或者密码错误!");
              request.setAttribute("error", "登录失败,用户名或者密码错误!");
              //实现服务器跳转,使用转发,共享request
              RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
              requestDispatcher.forward(request, response);
          }
      }
    }
    
    
  2. main.jsp

<%@ page import="com.example.login_demo.pojo.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>主页面</title>
</head>
<body>
<h1>登录成功!欢迎 <%=(User)session.getAttribute("user")%> !</h1>
</body>
</html>

  1. login.jsp

    <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    <!DOCTYPE html>
    <html>
    <head>
     <title>JSP - login</title>
    </head>
    <body>
    <form action="loginServlet" method="post">
     用户名:<input type="text" name="userName"><br>
     密  码:<input type="text" name="password"><br>
     <span style="color: red"><%=request.getAttribute("error") == null?"":request.getAttribute("error")%></span><br>
     <input type="submit" value="登录">
    </form>
    </body>
    </html>
    
  2. 测试:

    在这里插入图片描述

文章来源:https://blog.csdn.net/CAUC_lin/article/details/135423929
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。