简单的HTML+Servlet+JDBC登录案例

HTML+Servlet+JDBC登录案例

思路

简单的HTML+Servlet+JDBC登录案例_第1张图片

我们发现:所有的代码:接收请求、查询数据库、封装对象、作出响应的代码都在Servlet中实现,这不符合程序的单一职责原则。应该将各自的代码抽取成各自的类。即

Servlet【控制层】 只做接收请求,做出响应

Dao【数据访问层】只做数据库操作

Service【业务层】只做业务逻辑,判断和数据的处理

这就是三层架构

简单的HTML+Servlet+JDBC登录案例_第2张图片

搭建项目框架

1、创建三层架构的包

简单的HTML+Servlet+JDBC登录案例_第3张图片

2、创建数据库

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  `phone` varchar(255) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  
 
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

3、创建实体类

package com.lyc.pojo;


import java.sql.Date;

public class User {
    private int id;
    private String username;
    private String password;
    private int age;
    private String address;
    private String phone;
    private Date birthday;

    public User() {
    }

    public User(int id, String username, String password, int age, String address, String phone, Date birthday) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.age = age;
        this.address = address;
        this.phone = phone;
        this.birthday = birthday;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                ", phone='" + phone + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}


4、创建JDBC工具类

package com.lyc.utils;

import java.sql.*;

public class DBUtil {
    private static Connection conn = null;
    private static final String URL = "jdbc:mysql://localhost:3306/test";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "******";

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection(){
        try {
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void closeAll(Connection conn, PreparedStatement ps){
        try {
            ps.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void closeAll(Connection conn, PreparedStatement ps, ResultSet rs){
        try {
            rs.close();
            ps.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

5、登录页面

<%--
  Created by IntelliJ IDEA.
  User: ASUS
  Date: 2022/9/2
  Time: 18:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>登录title>
  head>
  <body>
      <form action="LoginServlet" method="post">
          <table border="1" style="text-align: center">
              <tr>
                  <td> 用户名:td>
                  <td>
                      <input type="text" name="username">
                  td>
              tr>
              <tr>
                  <td> 密码:td>
                  <td>
                      <input type="password" name="password">
                  td>
              tr>
              <tr>
                  <td colspan="2">
                      <input type="submit" value="登录">
                      <input type="reset">
                  td>
              tr>
          table>
      form>
  body>
html>

6、配置web.xml文件


<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>LoginServletservlet-name>
        <servlet-class>com.lyc.servlet.LoginServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>LoginServletservlet-name>
        <url-pattern>/LoginServleturl-pattern>
    servlet-mapping>
web-app>

7、编写Servlet程序

package com.lyc.servlet;

import com.lyc.pojo.User;
import com.lyc.service.impl.LoginServiceImpl;

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 {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        LoginServiceImpl service = new LoginServiceImpl();
        User user = service.login(username, password);

        if(user != null){
            req.getRequestDispatcher("/FindAllServlet").forward(req,resp);
        } else{
            req.getRequestDispatcher("/fail.jsp").forward(req,resp);
        }
    }
}

8、编写Service和ServiceImpl

先写接口方法

package com.lyc.service;

import com.lyc.pojo.User;

public interface LoginService {
    User login(String username, String password);
}

再实现该接口方法

package com.lyc.service.impl;

import com.lyc.dao.impl.LoginDaoImpl;
import com.lyc.pojo.User;
import com.lyc.service.LoginService;

public class LoginServiceImpl implements LoginService {

    @Override
    public User login(String username, String password) {
        LoginDaoImpl loginDao = new LoginDaoImpl();
        User user = loginDao.login(username, password);
        return user;
    }
}

9、编写Dao和DaoImpl

先写接口

package com.lyc.dao;

import com.lyc.pojo.User;

public interface LoginDao {
    User login(String username, String password);
}

再实现该接口

package com.lyc.dao.impl;

import com.lyc.dao.LoginDao;
import com.lyc.pojo.User;
import com.lyc.utils.DBUtil;

import java.sql.*;

public class LoginDaoImpl implements LoginDao {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    User user = null;
    @Override
    public User login(String username, String password) {
       conn = DBUtil.getConnection();
        String sql = "select * from user where username=? and password = ?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            if (rs.next()){
                int id = rs.getInt("id");
                String sqluser = rs.getString("username");
                String sqlpwd = rs.getString("password");
                int age = rs.getInt("age");
                String address = rs.getString("address");
                String phone = rs.getString("phone");
                Date birthday = rs.getDate("birthday");
                user = new User(id,sqluser,sqlpwd,age,address,phone,birthday);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeAll(conn,ps,rs);
        }
        return user;
    }
}

整个项目的框架结构
简单的HTML+Servlet+JDBC登录案例_第4张图片

你可能感兴趣的:(java基础,前端,servlet,html,java)