Servlet+JDBC实现登陆功能的小例子

文章目录

  • 用户登录案例需求:
    • 分析
    • 步骤
    • 结果

用户登录案例需求:

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

分析

步骤

文件树展示
Servlet+JDBC实现登陆功能的小例子_第1张图片
1.创建项目,配置文件,jar包
Servlet+JDBC实现登陆功能的小例子_第2张图片
druid.properties配置文件

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

2.登陆界面login.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <form action="/Servlet_Demo/loginServlet" method="post">
        <input type="text" name="username" placeholder="用户名">
        <input type="text" name="password" placeholder="密码">
        <input type="submit" value="提交">
    form>
body>
html>

3.数据库准备

CREATE DATABASE servlettest;
USE servlettest;
CREATE TABLE USER(
	id INT PRIMARY KEY AUTO_INCREMENT,
	username VARCHAR(32) UNIQUE NOT NULL,
	PASSWORD VARCHAR(32) NOT NULL
		);
INSERT INTO USER VALUES(null,"Ray",123);

4.创建User类,这个是用户实体类

package text.userclass;

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 + '\'' +
                '}';
    }
}

5.工具类JDBCUtils,这个工具类是老朋友了,使用Durid数据库连接池来获得数据库连接池对象。因为后面会使用JdbcTemplate,它会帮我们归还数据库连接,所以这里就不再写归还。

package text.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtils {
    //数据库连接池对象
    private static DataSource ds;
    //Druid数据库连接池配置
    static{
        try {
            Properties pro=new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds=DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //返回数据库连接池对象
    public static DataSource getDatasource(){
        return ds;
    }
    //返回数据库连接
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
}

6.创建UserDao类,这个类提供了login方法,我们用User用户实体类就可以在这里判断用户名和密码是否正确

package text.dao;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import text.userclass.User;
import text.utils.JDBCUtils;

public class UserDao {
    private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDatasource());
    /**
     * 用户登陆的方法
     * @param loginusername 用户登陆名和密码
     * @return 所有用户信息
     */
    public User login(User loginusername){
        try {
            String sql="select * from USER where username=? and password=?";
            User user = template.queryForObject(sql,
                    new BeanPropertyRowMapper<User>(User.class),
                    loginusername.getUsername(), loginusername.getPassword());
            return user;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return null;
        }
    }
}

7.在准备工作完成后,我这里写了一个Main类来测试一下连接是否正确(也可以不写该类)

package text;

import org.junit.Test;
import text.dao.UserDao;
import text.userclass.User;

public class main {
    @Test
    public void userlogin(){
        User user=new User();
        user.setUsername("Ray");
        user.setPassword("123");
        User loginuser = new UserDao().login(user);
        System.out.println(loginuser);
    }
}

Servlet+JDBC实现登陆功能的小例子_第3张图片
8.测试完毕,开始写Servlet类,首先我们需要一个LoginServlet类来判断用户是否通过验证,再去跳转到对应的页面

这里如果一个个去获取值的话,再一个个封装成User类的话太麻烦了。采用工具类BeanUtils的populate()方法来简化这个过程

package text.web;

import org.apache.commons.beanutils.BeanUtils;
import text.dao.UserDao;
import text.userclass.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;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@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 user=new User();
//        user.setUsername(username);
//        user.setPassword(password);
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user=new User();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //使用UserDao来判断数据库中是否有匹配数据
        UserDao userDao=new UserDao();
        User login = userDao.login(user);
        if(login!=null){
            request.setAttribute("user",user);
            request.getRequestDispatcher("/successServlet").forward(request,response);
        }else{
            request.getRequestDispatcher("/failServlet").forward(request,response);
        }
    }

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

9.实现成功和失败的两种Servlet类
SuccessServlet类

package text.web;

import text.userclass.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 {
        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);
    }
}

FailServlet类

package text.web;

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);
    }
}

结果

登陆login.html
Servlet+JDBC实现登陆功能的小例子_第4张图片
输入对的数据
Servlet+JDBC实现登陆功能的小例子_第5张图片
输入错的数据
Servlet+JDBC实现登陆功能的小例子_第6张图片

你可能感兴趣的:(web)