文章目录

说明

NOTE:文中所用到的jar包均在本博客”专业软件software”中可查找
所需工具:

软件类:

Mysql
SQLyog
IDEA


JAR包类:

JSTL包
Bean包
JDBC包

用户类实现不一定是固定数据,且代码数量过多,故封装为类

创建用户类[User]

package Bean;

import java.util.Date;

public class User {
        private int id;
        private String username;
        private String password;
        private String email;
        private Date 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 String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        public Date getBirthday() {
            return birthday;
        }
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
}

创建用户信息类[UserDao]

package Dao;

import Bean.User;
import utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    // 添加用户的操作
    public boolean insert(User user) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            // 获得数据的连接
            conn = JDBCUtils.getConnection();

            // 发送SQL语句
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String birthday = sdf.format(user.getBirthday());
            String sql = " INSERT INTO users(NAME,PASSWORD,email,birthday) VALUES(?,?,?,?)";
            // 获得Statement对象
            stmt = conn.prepareStatement(sql);
            stmt.setString(1,user.getUsername());
            stmt.setString(2,user.getPassword());
            stmt.setString(3,user.getEmail());
            stmt.setString(4,birthday);
            int num = stmt.executeUpdate();
            if (num > 0) {
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(rs, stmt, conn);
        }
        return false;
    }
    //查询所有,返回的是多条数据对应的bean对象
    public List<User> getall(){
        List<User> list=new ArrayList<>();//删除集合存储查询到的所有对象
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet set=null;
        try {
            connection = JDBCUtils.getConnection();//连接数据库
            String sql = "select * from users";//SQL语句
            statement = connection.prepareStatement(sql);//获得preparedStatment对象
            set = statement.executeQuery();//执行SQL语句
            //操作结果集
            while (set.next()) {
                //获得每条记录各个字段的值
                int id = set.getInt("id");
                String name = set.getString("name");
                String password = set.getString("password");
                String email = set.getString("email");
                String birthday = set.getString("birthday");
                //将各个字段的值封装进bean对象
                User user = new User();
                user.setId(id);
                user.setUsername(name);
                user.setPassword(password);
                user.setEmail(email);
                user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));//要把字符串birthday转换成Date
                //将user放入集合
                list.add(user);
            }
            return list;//将集合返回给调用者
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            JDBCUtils.release(set,statement,connection);
        }
        return null;//如果发生异常,返回null
    }
}

创建数据库工具类[JDBCUtil]

package utils;
import java.sql.*;
public class JDBCUtils{
    //获得数据库连接
public static Connection getConnection() throws Exception{
    Statement stmt=null;
    ResultSet rs=null;
    Connection conn=null;

            // 1. 注册数据库的驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2.通过DriverManager获取数据库连接
            String url = "jdbc:mysql://localhost:3306/jdbc";
            String username = "root";
            String password = "150706";
            conn = DriverManager.getConnection(url, username,
                    password);
            return conn;
        }

        //释放资源
    public static void release(ResultSet rs,Statement statement,Connection conn){
        if(rs!=null){
            try{
                rs.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
            rs=null;
        }
        if(statement!=null){
            try{
                statement.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
            statement=null;
        }
        if(conn!=null){
            try{
                conn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
            conn=null;
        }

        }
        public static void release(Statement statement,Connection connection){
            if(statement!=null){
                try{
                    statement.close();
                }catch(SQLException e){
                    e.printStackTrace();
                }
                statement=null;
            }
            if(connection!=null){
                try{
                    connection.close();
                }catch(SQLException e){
                    e.printStackTrace();
                }
                connection=null;
            }
        }
}
注:每次需要使用数据库此三项必不可少

实现向数据库添加信息功能

package Servlet;

import Bean.User;
import Dao.UserDao;

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 javax.xml.crypto.Data;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out=response.getWriter();
        //获取参数值
        String name=request.getParameter("username");
        String password=request.getParameter("password");
        String email=request.getParameter("email");
        String birthday=request.getParameter("birthday");
        //数据封装成User-----bean对象
        User user=new User();
        user.setUsername(name);
        user.setPassword(password);
        user.setEmail(email);
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        Date d= null;
        try{
            d=format.parse(birthday);
        }catch (ParseException e){
            e.printStackTrace();
        }
        user.setBirthday(d);//需要将String类型的birthday转换成Date
        //添加进数据库
        boolean f=new UserDao().insert(user);
        if (f){
            out.print("添加成功!");
        }else{
            out.print("添加失败!");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/4/22
  Time: 8:43
  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 action="/AddServlet" method="post">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    邮箱:<input type="text" name="email"><br>
    出生日期:<input type="date" name="birthday"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

实现查询数据库信息功能

package Servlet;

import Bean.User;
import Dao.UserDao;

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.io.PrintWriter;
import java.util.List;

@WebServlet("/QueryAllServlet")
public class QueryAllServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out=response.getWriter();
//        -----分割线-----
        List<User> list=new UserDao().getall();
        request.setAttribute("list",list);
        request.getRequestDispatcher("/queryall.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/4/22
  Time: 10:35
  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 action="/QueryAllServlet" method="post">
    <input type="submit" value="查询所有数据"/>
</form>
<table border="1" width="600px" align="center">
    <tr>
        <td>用户名</td>
        <td>邮箱</td>
        <td>生日</td>
    </tr>
    <c:forEach items="${list}" var="user">
        <tr>
            <td>${user.username}</td>
            <td>${user.email}</td>
            <td>${user.birthday}</td>
        </tr>
    </c:forEach>
</table>
<%--测试项目:按ID去查询前三个--%>
<%--<form action="/QueryAllServlet" method="post">--%>
<%--    <input type="submit" value="查询前三数据"/>--%>
<%--</form>--%>
<%--<table border="1" width="600px" align="center">--%>
<%--    <tr>--%>
<%--        <td>用户名</td>--%>
<%--        <td>邮箱</td>--%>
<%--        <td>生日</td>--%>
<%--    </tr>--%>
<%--        <c:if test="${list.id>3}" var="pd">--%>
<%--            <tr>--%>
<%--                <td>${pd.username}</td>--%>
<%--                <td>${pd.email}</td>--%>
<%--                <td>${pd.birthday}</td>--%>
<%--            </tr>--%>
<%--        </c:if>--%>

</table>
</body>
</html>

项目下载

资源下载此资源下载价格为1猫粮,请先
客服QQ:2807306273