blog
原创

HTTP——Request用户登录案例

HTTP——Request用户登录案例

需求

用户在页面中输入用户名和密码,若用户名密码匹配,则跳转页面并提示用户登录成功,若不匹配则提示用户名或密码错误

  1. 编写html页面,让用户输入用户名和密码
  2. 用户提交后操作mysql,查找User表中的用户信息
  3. 若登录成功则转发至successServlet
  4. 若登录失败则转发至failServlet

准备

依赖jar包 在这里插入图片描述

实现

  1. HTML页面 login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
    <form method="post" action="/login/LoginServlet">
        <input type="text" placeholder="请输入用户名" name="username">
        <input type="password" placeholder="请输入密码" name="password">
        <input type="submit" value="登录">
    </form>
</body>
</html>
  1. 创建数据库环境
CREATE DATABASE login;
USE login;
CREATE TABLE user(
	id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(32) UNIQUE NOT NULL,
    password VARCHAR(32) NOT NULL,
);
  1. Druid数据库连接池配置文件 druid.properties
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///login?serverTimezone=Asia/Shanghai
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000
  1. 创建User类,封装用户信息
package login.domain;

// 用户实体类
public class User {

    //  定义User的成员变量
    private int id;
    private String username;
    private String password;

    // 定义Getter和Setter
    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 + '\'' +
                '}';
    }
}
  1. 创建JDBCUtils工具类
package login.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

// JDBC工具类
public class JDBCUtils {

    private static DataSource ds;

    static {
        try {
            // 加载配置文件
            Properties pro = new Properties();
            InputStream stream = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(stream);

            // 初始化连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取连接池对象
    public static DataSource getDataSource(){
        return ds;
    }

    // 获取Connection对象
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
}
  1. 创建UserDao类,提供登录方法并操作数据库
package login.dao;

import login.domain.User;
import login.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

// 操作数据库中User表的类
public class UserDao {

    // 声明JDBCTemplate对象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    // 定义登录方法
    public User login(User loginUser){
        try {
            // 编写SQL
            String sql = "select * from user where username = ? and password = ?";
            // 调用Query方法并返回查询到的user对象
            User user = template.queryForObject(sql,
                    new BeanPropertyRowMapper<User>(User.class),
                    loginUser.getUsername(),loginUser.getPassword());
            // 若有对应查询结果,则返回该user对象
            return user;
        } catch (DataAccessException e) {
            // 若queryForObject报错,则查询不到对应用户,返回null
            return null;
        }
    }
}
  1. 编写loginServlet,获取请求参数,调用登录方法并判断登录结果
package login.servlet;

import login.dao.UserDao;
import login.domain.User;

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("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码
        request.setCharacterEncoding("utf-8");
        // 获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 封装User对象
        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);
        // 调用login方法
        UserDao dao = new UserDao();
        User user = dao.login(loginUser);
        // 判断user是非为空
        if (user == null){
            // 登录失败,转发至failServlet
            request.getRequestDispatcher("failServlet").forward(request,response);
        } else {
            // 登陆成功
            // 存储查询后的user对象
            request.setAttribute("user",user);
            // 转发至successServlet
            request.getRequestDispatcher("successServlet").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
  1. 编写successServlet,提供登录成功后的内容显示
package login.servlet;

import login.domain.User;

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("/successServlet")
public class successServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置页面编码
        response.setContentType("text/html;charset=utf-8");
        // 获取存储的user对象
        User user = (User) request.getAttribute("user");
        // 若user不为空,则输出文字到页面
        if (user != null) {
            response.getWriter().write( user.getUsername() + "--登录成功");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
  1. 编写failServlet,提供登录失败的页面显示
package login.servlet;

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("/failServlet")
public class failServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置页面编码
        response.setContentType("text/html;charset=utf-8");
        // 输出文字到页面
        response.getWriter().write("登录失败,用户名或密码错误");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

案例效果

登录界面

在这里插入图片描述

登录成功

在这里插入图片描述

登录失败

在这里插入图片描述

HTTP
  • 作者:Melonico
  • 发表时间:2021-03-15 17:50
  • 更新时间:2021-03-15 17:50

评论

暂无评论,快来发表第一个评论吧!
留言
TOP