JavaWeb实现用户登录【HTML+MySQL+JDBCTemplate+Servlet+Druid连接池】

JavaWeb实现用户登录【HTML+MySQL+JDBCTemplate+Servlet+Druid连接池】

一、用户登录案例需求:

  1. 编写login.html登录页面,username & password 两个输入框
  2. 使用Druid数据库连接池技术,操作mysql,数据库中user表
  3. 使用JdbcTemplate技术封装JDBC
  4. 登录成功跳转到SuccessServlet展示:登录成功!用户名,欢迎您
  5. 登录失败跳转到FailServlet展示:登录失败,用户名或密码错误

二、用户登录案例分析:

三、创建项目

  1. 创建JavaWeb项目,将druid.properties放入src文件中。druid.properties文件的相关内容如下:
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///db_student_manager_web?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000
  1. 在web/WEB-INF下创建lib文件,将用到JDBCTemplate的相关jar包,全部导入lib文件中。对于想要了解其相关内容,可以点击右侧链接JDBCTemplate的相关知识
  • jar包的相关目录如下:
    JavaWeb实现用户登录【HTML+MySQL+JDBCTemplate+Servlet+Druid连接池】_第1张图片
  1. 将jar包Add as Librsry;然后导入html页面,login.html中的form表单的action路径的写法是:虚拟目录+Servlet的资源路径

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <form action="" method="post">
        用户名:<input type="text" name="username"> <br>
        密码:<input type="password" name="password"><br>

        <input type="submit" value="登录">
    form>
body>
html>

四、 创建数据库的环境

  1. 创建USER表格
CREATE TABLE `user` (
	`id` INT NOT NULL AUTO_INCREMENT,
	`username` VARCHAR ( 32 ) NOT NULL,
	`password` VARCHAR ( 32 ) NOT NULL,
	PRIMARY KEY ( `id` ),
UNIQUE KEY `username` ( `username` ) 
) ENGINE = INNODB DEFAULT CHARSET = utf8;
  1. 在user表格里面添加数据,用于后面的登录操作
    在这里插入图片描述

三、编写代码

  1. 创建cn.itcast.domain,创建类User
package cn.itcast.domain;
/**
 * 用户的实体类
 */
public class User {
    private int id;
    private String username;
    private String 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 + '\'' +
                '}';
    }
}
  1. 创建cn.itcast.dao,创建类UserDao,提供login方法
package cn.itcast.dao;
import cn.itcast.domain.User;
import cn.itcast.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 操作数据库中User表的类
 */
public class UserDao {
    //声明JDBCTemplate对象共用
    protected JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    /**
     * 登录方法
     * @param loginUser 只有用户名和密码
     * @return user包含用户全部数据 , 没有查询到,返回null
     */
    public User login(User loginUser){
        try {
            //1.编写sql
            String sql = "select * from user where username = ? and password = ?";
            //2.调用query方法
            User user = template.queryForObject(sql,
                    new BeanPropertyRowMapper<User>(User.class),
                    loginUser.getUsername(), loginUser.getPassword());
            return user;
        }catch (DataAccessException e){
            e.printStackTrace();
            return null;
        }
    }
}
  1. 创建cn.itcast.util,创建JDBC工具类,使用Druid连接池
package cn.itcast.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工具类,使用Druid连接池
 */
public class JDBCUtils {

    private static DataSource ds;
    static {
        try {
            //1.加载配置文件
            Properties pro = new Properties();
            //使用ClassLoader加载配置文件,获取字节输入流
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);
            //2.初始化连接池对象
            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. 创建cn.itcast.web.servlet,创建LoginServlet类
package cn.itcast.web.servlet;
import cn.itcast.dao.UserDao;
import cn.itcast.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 doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置编码
        req.setCharacterEncoding("utf-8");
        //2.获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //3.封装user对象
        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);

        //4.调用UserDao的login方法
        UserDao dao = new UserDao();
        User user = dao.login(loginUser);

        //5.判断user
        if (user == null){
            //登陆失败
            req.getRequestDispatcher("/FailServlet").forward(req,resp);
        }else {
            //登录成功
            //存储数据
            req.setAttribute("user",user);
            //转发
            req.getRequestDispatcher("/SuccessServlet").forward(req,resp);
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
  1. 编写类FailServlet和类SuccessServlet的跳转页面。
  • FailServlet类文件:
package cn.itcast.web.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);
    }
}

  • SuccessSuServlet类文件:
package cn.itcast.web.servlet;

import cn.itcast.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("/SuccessSuServlet")
public class SuccessServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getAttribute("user");

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

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

五、登录效果演示

JavaWeb实现用户登录【HTML+MySQL+JDBCTemplate+Servlet+Druid连接池】_第2张图片



扩展:优化代码

截止到此,已经实现了通过使用JavaWeb来实现用户登录的功能,但是对于代码的上述的编写,还是有些欠缺的地方;在LoginServlet类文件中将username,password都封装成了对象,上述的页面也就只有两个参数想要进行数据封装;那么要是注册页面,需要很多的数据项需要封装的话,会造成代码冗余。
那么我们可以通过下面的方法将数据一次性全部获取,然后封装。

BeanUtils工具类,简化数据封装

  1. 将commons-beanutils-1.8.0.jar包放入web/WEB-INF/ilb文件中,然后 Add as Library。
  2. 重新编写LoginServlet类。
package cn.itcast.web.servlet;
import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
import org.apache.commons.beanutils.BeanUtils;
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;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置编码
        req.setCharacterEncoding("utf-8");
        
        //2.获取所有请求参数
        Map<String, String[]> map = req.getParameterMap();
        ///3.创建User对象
        User loginUser = new User();
        //3.2使用BeanUtils封装
        try {
            BeanUtils.populate(loginUser,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //4.调用UserDao的login方法
        UserDao dao = new UserDao();
        User user = dao.login(loginUser);

        //5.判断user
        if (user == null){
            //登陆失败
            req.getRequestDispatcher("/FailServlet").forward(req,resp);
        }else {
            //登录成功
            //存储数据
            req.setAttribute("user",user);
            //转发
            req.getRequestDispatcher("/SuccessServlet").forward(req,resp);
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
  • BeanUtils工具类,用于JavaBean,封装数据。

方法:

  1. setProperty()
  2. getProperty()
  3. populate(Obgect obj,Map map):将map集合的键值对信息,封装到对应的JavaBean集合中。

你可能感兴趣的:(JavaWEB基础)