实现一个简单用户登录案例 Tomcat+Servlet+jdbc+mysql+html

简单用户登录案例

    • 一、创建数据库环境
    • 二、搭建web环境,Tomcat服务器
    • 三、简单登录页面HTML
    • 四、导入所需项目jar包
    • 五、编写JavaBean标准类
    • 六、[Druid连接池](https://blog.csdn.net/weixin_45627031/article/details/106535010)
        • 1.定义配置文件
        • 2. 定义JDBCUtils工具类
        • 3.使用工具类操作表User
    • 七、定义Servlet类
        • 1.Servlet
        • 2.登录错误显示页面 (failServlet)
        • 3.成功登录显示页面 (SuccessServlet)

一、创建数据库环境

1.创建数据库
CREATE DATABASE USER;
2.使用USER表
USE USER;
3.建表
CREATE TABLE USER(	
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE NOT NULL,
PASSWORD VARCHAR(32) NOT NULL
);

二、搭建web环境,Tomcat服务器

1.Tomcat 服务器软件
2.Tomcat集成到IDEA中&部署web项目
3.项目布局
实现一个简单用户登录案例 Tomcat+Servlet+jdbc+mysql+html_第1张图片

三、简单登录页面HTML


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录title>
    <style>
        div{
            background-color: cornflowerblue;
        }
        h1{
            color: lightpink;
        }
    style>
head>

<body >
<div align="center">
<form action="/Servlet" method="post">
    <h1>用户登录页面h1>
    <input type="text" name="username" placeholder="请输入用户名"><br>
    <input type="password" name="password" placeholder="请输入密码"><br>
    <br>
    <input type="submit" value="登录">
form>
div>
body>
html>

代码实现效果:
实现一个简单用户登录案例 Tomcat+Servlet+jdbc+mysql+html_第2张图片

四、导入所需项目jar包

1.在web目录下创建WEB-INF目录,在创建lib
实现一个简单用户登录案例 Tomcat+Servlet+jdbc+mysql+html_第3张图片

2.百度网盘jar下载地址 提取码: e5wb

五、编写JavaBean标准类

package cn.domain;
public class User {
	//和数据库中对应,将来也可以增加作作注册页面
    private int id;
    private String username;
    private String password;
	//定义set get 方法
    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;
    }
	//重写 toString
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

六、Druid连接池

1.定义配置文件

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///user
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000

2. 定义JDBCUtils工具类

package cn.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;

public class JDBCUtils {
    /**
     * 编写jdbc工具类
     */
    private static DataSource ds;
    static {
        try {
            //加载配置文件
            Properties pro = new Properties();
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);
            //初始化连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取连接池对象
     */
    public static  DataSource getDateSource(){
        return ds;
    }
    /**
     * 获取连接connection对象
     */
    public static Connection getConnnection() throws SQLException {
        return ds.getConnection();
    }
}

3.使用工具类操作表User

package cn.dao;

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

public class UserDao {
    /**
     * 操作数据库user表的类
     */
    //声明JDBCTemplate对象共用
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDateSource());//需要一个数据库连接池

    public User login(User loginUser) {
        try {
            //编写sql
            String sql = "select * from USER where username = ? and password = ?";
            //调用query方法
            User user = template.queryForObject(sql,
                    new BeanPropertyRowMapper<User>(User.class), loginUser.getUsername(), loginUser.getPassword());
            return user;
        } catch (DataAccessException e) {
            e.printStackTrace();//记录日志
            return null;
        }
    }
}

七、定义Servlet类

1.Servlet

package cn.servletdome;

import cn.dao.UserDao;
import cn.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("/Servlet")
public class Servlet 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 user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //调用UserDao的login方法
        UserDao userDao=new UserDao();
        User login = userDao.login(user);
        if (login == null){
            //登录失败
            request.getRequestDispatcher("/failServlet").forward(request,response);
        }else {
            //登录成功
            //存储数据
            request.setAttribute("user",user);
            //登录成功
            request.getRequestDispatcher("/SuccessServlet").forward(request,response);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

2.登录错误显示页面 (failServlet)

package cn.servletdome;

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("登录失败,用户名或密码错误");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}

3.成功登录显示页面 (SuccessServlet)

package cn.servletdome;

import cn.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 {
        //获取request域中共享的user对象
        User user = (User) request.getAttribute("user");

        if (user != null) {
            //给页面写一句话
            //设置编码
            response.setContentType("text/html;charset=utf-8");
            //输出
            response.getWriter().write("登录成功!" + user.getUsername() + ",欢迎您");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        super.doGet(request, response);
    }
}

实现一个简单用户登录案例 Tomcat+Servlet+jdbc+mysql+html_第4张图片

你可能感兴趣的:(Web)