当前位置:主页 > 软件编程 > JAVA代码 >

JavaWeb使用mvc模式实现登录功能

时间:2022-11-22 10:57:04 | 栏目:JAVA代码 | 点击:

部署项目、环境搭建

 详细内容 

 1.导包 

 

  2.web >> index.jsp              web >> login.jsp              web >> success.jsp 

 

 1)  web >> index.jsp 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <a href="login.jsp">登录</a>
  </body>
</html>

 2)  web >> login.jsp  

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>登录</title>
  <style>
    #msg {
      color: red;
    }
  </style>
</head>
<body>
 
<form action="user" method="post">
  账号:<input type="text" name="userName"><span id="msg"><%=request.getAttribute("msg")%></span>

  密码:<input type="text" name="passWord">

  <input type="hidden" name="method" value="login">
  <input type="submit" value="登录">
</form>
 
</body>
</html>

 3)  web >> success.jsp  

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="constant.Con" %>
<html>
<head>
    <title>用户中心</title>
</head>
<body>
<%=request.getSession().getAttribute(Con.USER)%><h1 style="color: green">欢迎您</h1>
<a href="login.html">返回重新登录</a>
</body>
</html>

3.constant >> Con

package constant;
 
import java.io.Serializable;
 
public class Con implements Serializable {
    //session中保存用户登录信息
    public static final String USER = "user";
}

  entity >> User

package entity;
 
import java.io.Serializable;
 
public class User implements Serializable {
    private int id;
    private String userName;
    private String passWord;
 
    public User(int id, String userName, String passWord) {
        this.id = id;
        this.userName = userName;
        this.passWord = passWord;
    }
 
    public User() {
    }
 
    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;
    }
}

4.resources >> prop.properties 

driverClassName=com.mysql.cj.jdbc.Driver
urlName=jdbc:mysql://localhost:3306/myjdbc?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
userName=root
passwordName=root

  5.utils >> JDBCUtils

package utils;
 
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
 
/*
    JDBC工具类
 */
public class JDBCUtils {
    // 声明驱动的路径
    static String driverClass;
    static String url;
    static String user;
    static String password;
 
    /*
        静态代码块只会在加载class文件的时候执行一次,
        将注册驱动的代码由静态代码块来实现
     */
    static {
        // 创建属性集对象
        Properties prop = new Properties();
        // 将文件中的数据读取到属性集中
        try {
            //prop.properties
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("prop.properties");
            prop.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 获取key对应的value
        driverClass = prop.getProperty("driverClassName");
        url = prop.getProperty("urlName");
        user = prop.getProperty("userName");
        password = prop.getProperty("passwordName");
        try {
            // 加载驱动
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
 
    /*
        将获取资源的方法进行封装: Connection连接接口对象
     */
    public static Connection getConnection() throws SQLException, ClassNotFoundException {
        // 获取连接
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;
    }
 
    /*
        封装方法,用于释放资源
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 调用已经实现功能的方法直接使用
        close(connection, statement);
    }
 
    /*
        重载一个释放资源的代码,用来释放两个资源
     */
    public static void close(Connection connection, Statement statement) {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
}

6.servlet >> UserServlet

package servlet;
 
import constant.Con;
import service.UserService;
import service.impl.UserServiceImpl;
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(name = "user", urlPatterns = "/user")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
 
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置请求字符集为utf-8
        req.setCharacterEncoding("utf-8");
        //2.获取请求参数method,根据值调用不同方法处理业务
        String method = req.getParameter("method");
        if (method.equals("login")) {
            this.login(req, resp);
        }
    }
 
    //登录方法
    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取账号和密码
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");
        //2.调用service的方法处理登录
        boolean result = userService.checkUser(userName, passWord);
        if (result) {
            //true表示登录成功
            //转发跳转成功页面
            //req.getRequestDispatcher("/success.jsp").forward(req, resp);
            //将用户信息保存在session域对象中
            req.getSession().setAttribute(Con.USER, userName);
            //重定向跳转成功页面
            resp.sendRedirect(req.getContextPath() + "/success.jsp");
        } else {
            //false登录失败,返回登录页面
            req.setAttribute("msg", "账号密码不匹配");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }
}

7.service >> UserService        service >> impl >> UserServiceImpl

 

package service;
 
public interface UserService {
    //判断登录成功与否
    boolean checkUser(String userName, String passWord);
}
package service.impl;
 
import dao.UserDao;
import dao.impl.UserDaoImpl;
import entity.User;
import service.UserService;
import utils.JDBCUtils;
import java.sql.Connection;
import java.util.List;
 
public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
 
    @Override
    public boolean checkUser(String userName, String passWord) {
        // 连接对象
        Connection connection = null;
        try {
            //1.获取数据库连接
            connection = JDBCUtils.getConnection();
            //2.调用dao方法查询数据
            List<User> users = userDao.findUserByUserNameAndPassWord(connection, userName, passWord);
            //3.根据查询结果返回成功失败标志
            if (users.size() > 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            JDBCUtils.close(connection, null);
        }
    }
}

8.dao >> UserDao        dao >> impl >> UserDaoImpl

 

package dao;
 
import entity.User;
import java.sql.Connection;
import java.util.List;
 
public interface UserDao {
    //根据账号密码查询数据库,返回结果集
    List<User> findUserByUserNameAndPassWord(Connection connection, String userName, String passWord);
}
package dao.impl;
 
import dao.UserDao;
import entity.User;
import utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
 
public class UserDaoImpl implements UserDao {
    @Override
    public List<User> findUserByUserNameAndPassWord(Connection connection, String userName, String passWord) {
        // 发送sql语句对象
        PreparedStatement statement = null;
        List<User> userList = new ArrayList<>();
        try {
            connection = JDBCUtils.getConnection();
            // 获取Statement对象
            statement = connection.prepareStatement("select * from user where username = ? and password = ?");
            statement.setString(1, userName);
            statement.setString(2, passWord);
 
            ResultSet rs = statement.executeQuery();
            while (rs.next()) {
                User user = new User();
                int id = rs.getInt(1);
                String username = rs.getString(2);
                String password = rs.getString(3);
                user.setId(id);
                user.setUserName(username);
                user.setPassWord(password);
 
                userList.add(user);
            }
            return userList;
        } catch (Exception e) {
            e.printStackTrace();
            return userList;
        } finally {
            JDBCUtils.close(null, statement, null);
        }
    }
}

登录实现

1.首页 index.jsp

2.错误登录 login.jsp 

 

3. 正确登录 login.jsp  

 4. 登录成功 success.jsp

您可能感兴趣的文章:

相关文章