[JDBC封装与设计模式]JSP链接数据库实现用户登录,注册功能 通用模板

总览

环境

mysql  Ver 8.0.31

mysql-connector-j-8.0.31.jar

Tomcat 10.1.13

Navicat Premium 16

IntelliJ IDEA 2023.2.1

数据库

 建表代码

/*
 Navicat Premium Data Transfer

 Source Server         : localhost_3306
 Source Server Type    : MySQL
 Source Server Version : 80031
 Source Host           : localhost:3306
 Source Schema         : test

 Target Server Type    : MySQL
 Target Server Version : 80031
 File Encoding         : 65001

 Date: 22/10/2023 19:41:26
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `account` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  PRIMARY KEY (`account`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

代码

jdbc.properties 数据库配置信息

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test
uname=root
upwd=123456

BaseDao.java 数据库工具类

package com.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    public Connection conn=null;
    public PreparedStatement ps=null;
    //单例模式  整个项目只会连接一次数据库
    private static  String driver;
    private static String url;
    private static String uname;
    private static String upwd;
    //static修饰的属性,方法,代码块只会执行一次
    static{
        // 当前类加载属性文件转换成 输入流对象
        InputStream is=BaseDao.class.getClassLoader().getResourceAsStream("com/dao/jdbc.properties");
        Properties properties=new Properties();
        try {
            //属性文件对象加载输入流对象
            properties.load(is);
            //通过键获取属性文件的值
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            uname = properties.getProperty("uname");
            upwd = properties.getProperty("upwd");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //创建数据库的连接
    public void getConnection() {
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url,uname,upwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //关闭数据库链接
    public void closeConnection(){
        try {
            ps.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //查询模板方法
    public ResultSet selectSql(String sql,Object[] objs){
        ResultSet rs = null;
        if (conn!=null){
            try {
                ps = conn.prepareStatement(sql);
                if (objs!=null){
                    for (int i=0;i<objs.length;i++){
                        ps.setObject(i+1,objs[i]);
                    }
                }
                rs=ps.executeQuery();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return rs;
    }

    //增删改模板方法
    public int editSql(String sql,Object[] objs){
        int rs=0;
        if (conn!=null){
            try{
                ps = conn.prepareStatement(sql);
                if (objs!=null){
                    for (int i=0;i<objs.length;i++){
                        ps.setObject(i+1,objs[i]);
                    }
                }
                rs=ps.executeUpdate();
            }catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return rs;
    }
}

UserDao.java 需求接口

package com.dao;

import com.entity.User;

import java.util.List;

public interface UserDao {
    public List<User> findUserList(String account);
    public int addUser(User user);
    public int delUser(int id);
}

UserDaoImpl.java 实现类

package com.dao.impl;

import com.dao.BaseDao;
import com.dao.UserDao;
import com.entity.User;

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

public class UserDaoImpl extends BaseDao implements UserDao {
    @Override
    public List<User> findUserList(String account) {
        getConnection();
        List<User> userList=new ArrayList<>();
        try {
            String sql = "select * from user where account = ?";
            ResultSet rs = selectSql(sql,new Object[]{account});
            while (rs.next()){
                String password = rs.getString("password");
                userList.add(new User(account,password));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        closeConnection();
        return userList;
    }

    @Override
    public int addUser(User user) {
        getConnection();
        String sql="insert into user(account,password) values(?,?)";
        int rs = editSql(sql,new Object[]{user.getAccount(),user.getPassword()});
        closeConnection();
        return rs;
    }

    @Override
    public int delUser(int account) {
        getConnection();
        String sql="delete from user where account = ?";
        int rs = editSql(sql,new Object[]{account});
        closeConnection();
        return rs;
    }
}

User.java 实体

package com.entity;

public class User {
    private String account,password;
    public User() {
    }
    public User(String account, String password) {
        this.account = account;
        this.password = password;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "account='" + account + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

index.jsp 登录页面

<%--
  Created by IntelliJ IDEA.
  User: 53172
  Date: 2023/10/22
  Time: 16:37
  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="dologin.jsp" method="post">
    <table>
    <tbody>
    <tr>
      <td>用户名:</td>
      <td><input type="text" name="account"/></td>
    </tr>
    <tr>
      <td>密码:</td>
      <td><input type="password" name="password"/></td>
    </tr>
    </tbody>
    </table>
    <input type="submit" value="登录">
    <input type="button" value="注册" onclick="window.open('register.jsp')">
  </form>
  </body>
</html>

dologin.jsp 登录逻辑处理

<%@ page import="com.dao.UserDao" %>
<%@ page import="com.dao.impl.UserDaoImpl" %>
<%@ page import="java.util.List" %>
<%@ page import="com.entity.User" %><%--
  Created by IntelliJ IDEA.
  User: 53172
  Date: 2023/10/22
  Time: 17:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    String uact=request.getParameter("account");
    String upwd=request.getParameter("password");
    UserDao ud = new UserDaoImpl();
    List<User> userList = ud.findUserList(uact);
    if (!userList.isEmpty() && userList.get(0).getPassword().equals(upwd)){
        out.println("用户 "+uact+" 登录成功");
    }else {
        out.println("账号或密码错误");
    }
%>
<br/>
<input type="button" value="返回登录" onclick="window.open('index.jsp')">
<input type="button" value="返回注册" onclick="window.open('register.jsp')">
</body>
</html>

register.jsp 注册页面

<%--
  Created by IntelliJ IDEA.
  User: 53172
  Date: 2023/10/22
  Time: 18:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form name="reg" action="doregister.jsp" method="post">
    <table>
        <tbody>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="account"/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password"/></td>
        </tr>
        <tr>
            <td>重复密码:</td>
            <td><input type="password" name="rpassword"/></td>
        </tr>
        </tbody>
    </table>
    <input type="button" value="注册" onclick="doregister()">
</form>
<script>
    function doregister(){
        if (document.reg.account.value==null){
            alert("用户名不能为空!");
            return;
        }
        if (document.reg.password.value===document.reg.rpassword.value){
            reg.submit();
        }else{
            alert("两次密码输入不一致!");
        }
    }
</script>
</body>
</html>

doregister.jsp 注册逻辑处理

<%@ page import="com.dao.UserDao" %>
<%@ page import="com.dao.impl.UserDaoImpl" %>
<%@ page import="com.entity.User" %>
<%@ page import="java.util.List" %><%--
  Created by IntelliJ IDEA.
  User: 53172
  Date: 2023/10/22
  Time: 18:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    String uact=request.getParameter("account");
    String upwd=request.getParameter("password");
    UserDao ud = new UserDaoImpl();
    int rs=0;
    try{
        rs=ud.addUser(new User(uact,upwd));
    }catch (Exception e){
        e.printStackTrace();
    }
    if (rs==1){
        out.println("恭喜用户"+uact+"注册成功!");
    }else {
        out.println("注册失败,可能用户名:"+uact+"已存在!");
    }
%>
<br/>
<input type="button" value="返回登录" onclick="window.open('index.jsp')">
<input type="button" value="返回注册" onclick="window.open('register.jsp')">
</body>
</html>

下载

李某人的个人主页 (ox3fffff.cn)

右下加秘密入口提取码:JSP

  • 7
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
好的,以下是具体的代码和步骤: 1. 创建数据库和表 首先需要在MySQL中创建一个名为“test”的数据库,然后在该数据库中创建一个名为“products”的表,表结构如下: ``` CREATE TABLE `products` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `price` double NOT NULL, `description` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` 2. 创建JavaBean 创建一个名为“Product”的JavaBean,包含id、name、price和description四个属性,以及对应的getters和setters方法。 ``` public class Product { private int id; private String name; private double price; private String description; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } ``` 3. 创建查询逻辑 创建一个名为“QueryProductServlet”的Servlet,实现商品查询的逻辑。 ``` public class QueryProductServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String QUERY_PRODUCT = "queryProduct.jsp"; private static final String DISPLAY_PRODUCT = "displayProduct.jsp"; private static final String DISPLAY_ALL_PRODUCT = "displayAllProduct.jsp"; private static final String ERROR = "error.jsp"; private ProductDao productDao = new ProductDao(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String forward = ""; String productId = request.getParameter("productId"); if (productId == null || productId.isEmpty()) { forward = QUERY_PRODUCT; } else { try { int id = Integer.parseInt(productId); Product product = productDao.getProductById(id); if (product != null) { request.setAttribute("product", product); forward = DISPLAY_PRODUCT; } else { request.setAttribute("error", "Product not found"); forward = ERROR; } } catch (NumberFormatException e) { request.setAttribute("error", "Invalid product ID"); forward = ERROR; } } request.getRequestDispatcher(forward).forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String forward = ""; List<Product> products = productDao.getAllProducts(); if (products != null && !products.isEmpty()) { request.setAttribute("products", products); forward = DISPLAY_ALL_PRODUCT; } else { request.setAttribute("error", "No products found"); forward = ERROR; } request.getRequestDispatcher(forward).forward(request, response); } } ``` 上面的代码中,QueryProductServlet包含了doGet和doPost两个方法,分别对应用户输入商品号进行单个商品查询和查询所有商品信息的操作。当用户输入商品号时,QueryProductServlet会调用ProductDao对象的getProductById方法从数据库中查询商品信息,并将查询结果存入request对象中,最后转发到displayProduct.jsp页面显示查询结果。当用户不输入商品号时,QueryProductServlet会调用ProductDao对象的getAllProducts方法查询所有商品信息,并将查询结果存入request对象中,最后转发到displayAllProduct.jsp页面显示查询结果。 4. 创建数据访问对象 创建一个名为“ProductDao”的类,实现对产品数据的访问操作。 ``` public class ProductDao { private static final String SELECT_PRODUCT_BY_ID = "SELECT * FROM products WHERE id = ?"; private static final String SELECT_ALL_PRODUCTS = "SELECT * FROM products"; public Product getProductById(int productId) { Product product = null; try (Connection conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(SELECT_PRODUCT_BY_ID)) { stmt.setInt(1, productId); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { product = new Product(); product.setId(rs.getInt("id")); product.setName(rs.getString("name")); product.setPrice(rs.getDouble("price")); product.setDescription(rs.getString("description")); } } } catch (SQLException e) { e.printStackTrace(); } return product; } public List<Product> getAllProducts() { List<Product> products = new ArrayList<>(); try (Connection conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(SELECT_ALL_PRODUCTS); ResultSet rs = stmt.executeQuery()) { while (rs.next()) { Product product = new Product(); product.setId(rs.getInt("id")); product.setName(rs.getString("name")); product.setPrice(rs.getDouble("price")); product.setDescription(rs.getString("description")); products.add(product); } } catch (SQLException e) { e.printStackTrace(); } return products; } private Connection getConnection() throws SQLException { String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "root"; return DriverManager.getConnection(url, user, password); } } ``` 上面的代码中,ProductDao类包含了getProductById和getAllProducts两个方法,分别对应单个商品查询和查询所有商品信息的操作。在getProductById方法中,使用了PreparedStatement对象执行SQL查询,并将查询结果封装成Product对象返回。在getAllProducts方法中,使用了PreparedStatement对象执行SQL查询,并将查询结果封装成List<Product>返回。 5. 创建JSP页面 创建一个名为“queryProduct.jsp”的JSP页面,用于用户输入商品号进行单个商品查询。 ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Query Product</title> </head> <body> <h1>Query Product</h1> <form method="get" action="QueryProductServlet"> <label>Product ID:</label> <input type="text" name="productId"><br> <input type="submit" value="Query"> </form> </body> </html> ``` 创建一个名为“displayProduct.jsp”的JSP页面,用于显示单个商品查询的结果。 ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Display Product</title> </head> <body> <h1>Display Product</h1> <table border="1" cellpadding="5"> <tr> <th>ID</th> <th>Name</th> <th>Price</th> <th>Description</th> </tr> <c:if test="${not empty product}"> <tr> <td>${product.id}</td> <td>${product.name}</td> <td>${product.price}</td> <td>${product.description}</td> </tr> </c:if> </table> <br> <a href="queryProduct.jsp">Back to Query Product</a> </body> </html> ``` 创建一个名为“displayAllProduct.jsp”的JSP页面,用于显示所有商品信息的查询结果。 ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Display All Products</title> </head> <body> <h1>Display All Products</h1> <table border="1" cellpadding="5"> <tr> <th>ID</th> <th>Name</th> <th>Price</th> <th>Description</th> </tr> <c:forEach items="${products}" var="product"> <tr> <td>${product.id}</td> <td>${product.name}</td> <td>${product.price}</td> <td>${product.description}</td> </tr> </c:forEach> </table> <br> <a href="queryProduct.jsp">Back to Query Product</a> </body> </html> ``` 创建一个名为“error.jsp”的JSP页面,用于显示错误信息。 ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Error</title> </head> <body> <h1>Error</h1> <p>${error}</p> <br> <a href="queryProduct.jsp">Back to Query Product</a> </body> </html> ``` 6. 部署应用程序 将所有代码文件放入MyEclipse中的Web项目中,并将MySQL驱动程序(mysql-connector-java-5.1.46.jar)放入Web项目的WebContent/WEB-INF/lib目录中。最后,将Web项目部署到Tomcat服务器中。 7. 测试应用程序 在浏览器中访问http://localhost:8080/yourWebContext/queryProduct.jsp,输入商品号进行单个商品查询,或者直点击“Query All Products”按钮查询所有商品信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

0x3fffff

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值