Java简单案例:Servlet+JDBC实现登录功能

目录

  • 环境说明
  • Servlet+JDBC可能会遇到的坑
  • web项目分层说明
    • Bean层
    • Dao层
    • Service层
    • Controller层
  • Servlet 生命周期
  • 登录功能代码
    • 案例整体结构图
    • User类
    • DBUtil类
    • UserDao类
    • LoginServlet类
    • test类
    • web.xml
    • index.jsp

环境说明

  1. mysql 5.7版本
  2. mysql中创建sx的数据库,在sx数据库中有一张tb_user的表
  3. tb_user的表中有id,username,password 三个字段
  4. Tomcat 9.0版本
  5. 通过servlet+JDBC实现登录功能

Servlet+JDBC可能会遇到的坑

  • 在Servlet中使用jdbc运行报错提示java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

将mysql jar包放进tomcat服务器lib文件夹下

  • 通过浏览器调用Servlet,页面显示乱码或无法显示

在调用Servlet代码中添加request.setCharacterEncoding("utf-8");

web项目分层说明

以下是一般web项目分层说明

Bean层

Bean是实体层,里面存放实体类。通过提供符合一致性设计模式的公共方法将内部域暴露成员属性,set和get方法获取。

Dao层

Dao是持久层,访问数据库,实现数据库的真删改查。

Service层

Service是业务层,用来处理业务相关的事情。

Controller层

Controller是控制层,控制页面跳转等操作。

Servlet 生命周期

  1. 初始化
  2. 实例化
  3. 服务
  4. 销毁

登录功能代码

案例整体结构图

Java简单案例:Servlet+JDBC实现登录功能_第1张图片

User类

package bean;

public class User {
    public User() {
    }

    public User(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

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

DBUtil类

package dao.DBUtil;

import java.sql.*;

public class DBUtil {
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        /*加载驱动*/
        Class.forName("com.mysql.jdbc.Driver");

        /*创建连接*/
        Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/sx","root","");
        System.out.println("创建连接成功");
        return connection;
    }

    public static void closeAll(ResultSet resultSet, Statement statement, Connection connection) throws SQLException {

        if (resultSet!=null){
            resultSet.close();
        }
        if (statement!=null){
            statement.close();
        }
        if (connection!=null){
            connection.close();
        }
        System.out.println("所有连接关闭成功");
    }
}

UserDao类

这里由于是上一篇JDBC文章中修改的代码,所以大部分代码在这次是没用的。本次登录功能只用到了里面findUser方法。

package dao;

import DBUtil.DBUtil;
import bean.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    public List<User> findAll(){
        Connection connection= null;
        PreparedStatement statement= null;
        ResultSet resultSet=null;
        List<User> userList=new ArrayList<>();
        try {
            connection = DBUtil.getConnection();
            String sql="SELECT * FROM tb_user";
            statement = connection.prepareStatement(sql);
            resultSet=statement.executeQuery();
            while (resultSet.next()){
                User user=new User();
                user.setId(resultSet.getInt(1));
                user.setUsername(resultSet.getString(2));
                user.setPassword(resultSet.getString(3));
                userList.add(user);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                DBUtil.closeAll(resultSet,statement,connection);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return userList;
    }

    public User findUser(String name){
        Connection connection= null;
        PreparedStatement statement= null;
        ResultSet resultSet=null;
        User user = new User();
        try {
            connection = DBUtil.getConnection();
            String sql="SELECT * FROM tb_user WHERE username=?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,name );
            resultSet=statement.executeQuery();
            while (resultSet.next()){
                user.setId(resultSet.getInt(1));
                user.setUsername(resultSet.getString(2));
                user.setPassword(resultSet.getString(3));
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                DBUtil.closeAll(resultSet,statement,connection);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return user;
    }

    public void deleteById(int id){
        Connection connection= null;
        PreparedStatement statement= null;

        try {
            connection = DBUtil.getConnection();
            String sql="DELETE FROM tb_user WHERE id=?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, id);
            statement.executeUpdate();
            System.out.println("删除成功");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                DBUtil.closeAll(null,statement,connection);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public void add(User user){
        Connection connection= null;
        PreparedStatement statement= null;

        try {
            connection = DBUtil.getConnection();
            String sql="INSERT INTO tb_user(username,password) VALUE (?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1,user.getUsername());
            statement.setString(2,user.getPassword());
            statement.executeUpdate();
            System.out.println("增加成功");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                DBUtil.closeAll(null,statement,connection);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public void update(User user){
        Connection connection= null;
        PreparedStatement statement= null;

        try {
            connection = DBUtil.getConnection();
            String sql="UPDATE tb_user SET username=?,password=? WHERE id=?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,user.getUsername());
            statement.setString(2,user.getPassword());
            statement.setInt(3,user.getId());
            statement.executeUpdate();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                DBUtil.closeAll(null,statement,connection);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

}

LoginServlet类

package servlet;

import bean.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        UserDao userDao =new UserDao();
        User user = userDao.findUser(username);
        if (user.getUsername() == null){
            resp.getWriter().write("用户名不存在");
        }else if (!user.getPassword().equals(password)){
            resp.getWriter().write("密码错误!");
        }else {
            resp.getWriter().write("欢迎登录");
        }
    }
}

test类

这个类测试是否数据库访问正常。

import bean.User;
import dao.UserDao;

import java.util.List;

public class test {
    public static void main(String[] args) {
        UserDao userDao =new UserDao();
        String name ="test1";
        User userList = userDao.findUser(name);
        System.out.println(userList.getUsername());
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>servlet.LoginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    
</web-app>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>登录</title>
  </head>
  <body>

  <form action="/login" method="post">
    username:<input name="username" type="text">
    passsword:<input name="password" type="text">
    <input type="submit" value="login">
  </form>

  </body>
</html>

你可能感兴趣的:(Java)