当前位置: 代码迷 >> 综合 >> 【Java Web】9、CRUD
  详细解决方案

【Java Web】9、CRUD

热度:62   发布时间:2023-12-26 18:26:40.0

文章目录

  • CRUD
    • J2EE CRUD
    • 创建数据库与表
    • 创建动态 web 项目
    • 添加 jar 包和 css
    • 编写后台代码
      • 工具类(util)
      • 实体类(bean)
      • 数据库交互层(dao)
      • 控制层(servlet)
    • 编写前端页面
      • 添加页(add.jsp)
      • 列表页(list.jsp)
      • 更新页(update.jsp)
      • web.xml
    • 基于注解开发
    • 源码下载
  • 微信公众号

CRUD

J2EE CRUD

JavaWeb 入门首例,实现增加、删除、修改和查询功能。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MqGRAEEF-1642060823141)(http://47.107.171.232/easily-j/images/20190310/7fdbb26f-12ac-473c-89fd-1b282787fc53.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kJUU4oTD-1642060823145)(http://47.107.171.232/easily-j/images/20190310/697d8ff8-ec41-4b96-908d-6dc504814b89.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gGBbqJb5-1642060823147)(http://47.107.171.232/easily-j/images/20190310/f4f50b3e-240b-4be5-ae53-f8c68ec302b8.png)]

创建数据库与表

-- 创建数据库
create database readjava_study CHARACTER SET utf8 COLLATE utf8_general_ci;-- 创建学生信息表
CREATE TABLE `student` (`student_id` int(11) NOT NULL AUTO_INCREMENT,`student_number` varchar(255) DEFAULT NULL,`student_name` varchar(255) DEFAULT NULL,`student_password` varchar(255) DEFAULT NULL,`student_sex` int(11) DEFAULT NULL,PRIMARY KEY (`student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

创建动态 web 项目

需要注意一点,eclipse 需要将项目根目录改为 /,这样浏览器可以直接访问 localhost:8080 ,无需添加项目名字。idea 默认就是 / 无需更改。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bV62P8Xs-1642060823148)(http://47.107.171.232/easily-j/images/20190310/5a2b3138-fb88-4199-94ca-36a1b1dcb419.png)]

添加 jar 包和 css

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZxlM8p6A-1642060823149)(http://47.107.171.232/easily-j/images/20190310/73e76ccc-9f39-442a-a74f-8d4b3566e471.png)]

编写后台代码

工具类(util)

package com.readjava.util;import java.sql.Connection;
import java.sql.DriverManager;public class DbUtil {
    private static String url = "jdbc:mysql://localhost:3306/readjava_study"; // 数据库地址private static String userName = "root"; // 数据库用户名private static String passWord = "123456"; // 数据库密码private static Connection conn = null;/*** 获得数据库连接** @return*/public static Connection getConnection() {
    if (null == conn) {
    try {
    Class.forName("com.mysql.jdbc.Driver");conn = DriverManager.getConnection(url, userName, passWord);} catch (Exception e) {
    e.printStackTrace();}}return conn;}public static void main(String[] args) {
    System.out.println(getConnection());}
}

实体类(bean)

package com.readjava.bean;public class Student {
    private Integer studentId;private String studentName;private String studentPassword;private Integer studentSex;private String studentNumber;public Student() {
    }public Integer getStudentId() {
    return studentId;}public void setStudentId(Integer studentId) {
    this.studentId = studentId;}public String getStudentName() {
    return studentName;}public void setStudentName(String studentName) {
    this.studentName = studentName;}public String getStudentPassword() {
    return studentPassword;}public void setStudentPassword(String studentPassword) {
    this.studentPassword = studentPassword;}public Integer getStudentSex() {
    return studentSex;}public void setStudentSex(Integer studentSex) {
    this.studentSex = studentSex;}public String getStudentNumber() {
    return studentNumber;}public void setStudentNumber(String studentNumber) {
    this.studentNumber = studentNumber;}
}

数据库交互层(dao)

package com.readjava.dao;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;import com.readjava.bean.Student;
import com.readjava.util.DbUtil;public class StudentDao {
    /*** 所有学生信息** @return*/public List<Student> selectStudent() {
    List<Student> studentList = new ArrayList<>();Connection conn = DbUtil.getConnection();String sql = "select * from student";try {
    PreparedStatement pst = conn.prepareStatement(sql);ResultSet rst = pst.executeQuery();while (rst.next()) {
    Student student = new Student();student.setStudentId(rst.getInt("student_id"));student.setStudentName(rst.getString("student_name"));student.setStudentPassword(rst.getString("student_password"));student.setStudentSex(rst.getInt("student_sex"));student.setStudentNumber(rst.getString("student_number"));studentList.add(student);}rst.close();pst.close();} catch (SQLException e) {
    e.printStackTrace();}return studentList;}/*** 添加学生** @param student* @return*/public boolean addStudent(Student student) {
    String sql = "INSERT INTO student(student_name,student_password,student_sex,student_number) VALUES(?,?,?,?);";Connection conn = DbUtil.getConnection();try {
    PreparedStatement pst = conn.prepareStatement(sql);pst.setString(1, student.getStudentName());pst.setString(2, student.getStudentPassword());pst.setInt(3, student.getStudentSex());pst.setString(4, student.getStudentNumber());int count = pst.executeUpdate();pst.close();return count > 0 ? true : false;} catch (SQLException e) {
    e.printStackTrace();}return false;}/*** 更新学生信息** @param student* @return*/public boolean updateStudent(Student student) {
    String sql = "UPDATE student set student_name=?,student_password=?,student_sex=?,student_number=? WHERE student_id=?";Connection conn = DbUtil.getConnection();try {
    PreparedStatement pst = conn.prepareStatement(sql);pst.setString(1, student.getStudentName());pst.setString(2, student.getStudentPassword());pst.setInt(3, student.getStudentSex());pst.setString(4, student.getStudentNumber());pst.setInt(5, student.getStudentId());int count = pst.executeUpdate();pst.close();return count > 0 ? true : false;} catch (SQLException e) {
    e.printStackTrace();}return false;}/*** 删除学生信息** @param studentId* @return*/public boolean deleteStudent(int studentId) {
    String sql = "delete from student where student_id = ?";Connection conn = DbUtil.getConnection();try {
    PreparedStatement pst = conn.prepareStatement(sql);pst.setInt(1, studentId);int count = pst.executeUpdate();pst.close();return count > 0 ? true : false;} catch (SQLException e) {
    e.printStackTrace();}return false;}/*** 更具id查询学生** @param studentId* @return*/public Student getStudentById(int studentId) {
    Connection conn = DbUtil.getConnection();String sql = "select * from student where student_id = " + studentId;Student student = new Student();try {
    PreparedStatement pst = conn.prepareStatement(sql);ResultSet rst = pst.executeQuery();while (rst.next()) {
    student.setStudentId(rst.getInt("student_id"));student.setStudentName(rst.getString("student_name"));student.setStudentPassword(rst.getString("student_password"));student.setStudentSex(rst.getInt("student_sex"));student.setStudentNumber(rst.getString("student_number"));}rst.close();pst.close();} catch (SQLException e) {
    e.printStackTrace();}return student;}
}

控制层(servlet)

package com.readjava.servlet;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 com.readjava.bean.Student;
import com.readjava.dao.StudentDao;import java.io.IOException;@WebServlet("/add")
@SuppressWarnings("serial")
public class AddServlet extends HttpServlet {
    @Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.getRequestDispatcher("add.jsp").forward(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");Student student = new Student();String studentNumber = req.getParameter("studentNumber");String studentName = req.getParameter("studentName");String studentPassword = req.getParameter("studentPassword");int studentSex = Integer.parseInt(req.getParameter("studentSex"));student.setStudentNumber(studentNumber);student.setStudentName(studentName);student.setStudentPassword(studentPassword);student.setStudentSex(studentSex);StudentDao studentDao = new StudentDao();studentDao.addStudent(student);req.getRequestDispatcher("").forward(req, resp);}
}
package com.readjava.servlet;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 com.readjava.dao.StudentDao;import java.io.IOException;@WebServlet("/delete")
@SuppressWarnings("serial")
public class DeleteServlet extends HttpServlet {
    @Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    this.doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    int studentId = Integer.parseInt(req.getParameter("studentId"));StudentDao studentDao = new StudentDao();studentDao.deleteStudent(studentId);req.getRequestDispatcher("").forward(req, resp);}
}
package com.readjava.servlet;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 com.readjava.bean.Student;
import com.readjava.dao.StudentDao;import java.io.IOException;
import java.util.List;@WebServlet("")
@SuppressWarnings("serial")
public class ListServlet extends HttpServlet {
    @Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    this.doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    StudentDao studentDao = new StudentDao();List<Student> studentList = studentDao.selectStudent();req.setAttribute("studentList", studentList);req.getRequestDispatcher("list.jsp").forward(req, resp);}
}
package com.readjava.servlet;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 com.readjava.bean.Student;
import com.readjava.dao.StudentDao;import java.io.IOException;@WebServlet("/update")
@SuppressWarnings("serial")
public class UpdateServlet extends HttpServlet {
    @Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    int studentId = Integer.parseInt(req.getParameter("studentId"));StudentDao studentDao = new StudentDao();Student student = studentDao.getStudentById(studentId);req.setAttribute("student", student);req.getRequestDispatcher("update.jsp").forward(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");Student student = new Student();int studentId = Integer.parseInt(req.getParameter("studentId"));String studentNumber = req.getParameter("studentNumber");String studentName = req.getParameter("studentName");String studentPassword = req.getParameter("studentPassword");int studentSex = Integer.parseInt(req.getParameter("studentSex"));student.setStudentId(studentId);student.setStudentNumber(studentNumber);student.setStudentName(studentName);student.setStudentPassword(studentPassword);student.setStudentSex(studentSex);StudentDao studentDao = new StudentDao();studentDao.updateStudent(student);req.getRequestDispatcher("").forward(req, resp);}
}

编写前端页面

添加页(add.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html><head><meta charset="utf-8"><title>学生管理系统</title><link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"></head><body style="padding-top: 20px;"><div class="container"><div class="col-md-8 col-md-offset-2"><h1>添加学生</h1><br><form action="add" method="post"><div class="form-group"><label>学生编号</label><input type="text" class="form-control" name="studentNumber"></div><div class="form-group"><label>学生姓名</label><input type="text" class="form-control" name="studentName"></div><div class="form-group"><label>学生密码</label><input type="password" class="form-control" name="studentPassword"></div><div class="form-group"><label class="radio-inline"><input type="radio" name="studentSex" value="1" checked="checked"></label><label class="radio-inline"><input type="radio" name="studentSex" value="0"></label></div><div class="form-group"><button type="submit" class="btn btn-info">添加学生</button></div></form></div></div></body></html>

列表页(list.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html><head><meta charset="utf-8"><title>学生管理系统</title><link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css"></head><body style="padding-top: 20px;"><div class="container"><div class="col-md-8 col-md-offset-2"><h1>学生列表</h1><br><table class="table"><thead><td>学生ID</td><td>学生编号</td><td>学生姓名</td><td>学生密码</td><td>学生性别</td><td>操作</td></thead><tbody><c:forEach items="${studentList}" var="student"><tr><td>${
    student.studentId}</td><td>${
    student.studentNumber}</td><td>${
    student.studentName}</td><td>${
    student.studentPassword}</td><td><c:choose><c:when test="${student.studentSex == 0}"></c:when><c:when test="${student.studentSex == 1}"></c:when></c:choose></td><td><a class="btn btn-info btn-sm" href="/update?studentId=${student.studentId}">更 新</a><a class="btn btn-danger btn-sm" href="/delete?studentId=${student.studentId}">删 除</a></td></tr></c:forEach></tbody></table><button class="btn btn-success" onclick="window.location.href='/add'">添加学生</button><button class="btn btn-info" onclick="window.location.href='/'">学生列表</button></div></div></body></html>

更新页(update.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html><head><meta charset="utf-8"><title>学生管理系统</title><link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css"></head><body style="padding-top: 20px;"><div class="container"><div class="col-md-8 col-md-offset-2"><h1>更新学生</h1><br><form action="/update" method="post"><div class="form-group"><label>学生ID</label><input type="hidden" class="form-control" name=studentId value="${student.studentId}"></div><div class="form-group"><label>学生编号</label><input type="text" class="form-control" name="studentNumber" value="${student.studentNumber}"></div><div class="form-group"><label>学生姓名</label><input type="text" class="form-control" name="studentName" value="${student.studentName}"></div><div class="form-group"><label>学生密码</label><input type="password" class="form-control" name="studentPassword" value="${student.studentPassword}"></div><div class="form-group"><c:choose><c:when test="${student.studentSex == 1}"><label class="radio-inline"><input type="radio" name="studentSex" id="studentSex" value="1" checked="checked"></label><label class="radio-inline"><input type="radio" name="studentSex" id="studentSex" value="0"></label></c:when><c:when test="${student.studentSex == 0}"><label class="radio-inline"><input type="radio" name="studentSex" id="studentSex" value="1"></label><label class="radio-inline"><input type="radio" name="studentSex" id="studentSex" value="0" checked="checked"></label></c:when></c:choose></div><div class="form-group"><button type="submit" class="btn btn-info">更新学生</button></div></form></div></div></body></html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"><display-name>servlet-crud</display-name><welcome-file-list><welcome-file>list.jsp</welcome-file></welcome-file-list>
</web-app>

基于注解开发

一定很好奇为什么配置文件只修改了欢迎页面为 list.jsp,而没有类似 servlet-mapper 的配置,下面是原来的写法。

<servlet><servlet-name>AddServlet</servlet-name><servlet-class>com.readjava.AddServlet</servlet-class>
</servlet>
<servlet-mapping><servlet-name>AddServlet</servlet-name><url-pattern>/Add</url-pattern>
</servlet-mapping>

配置文件写法升级,通过注解的方式将繁琐的配置文件简化,上面的配置文件映射就可以改为以下注解:

@WebServlet("/add")
public class AddServlet extends HttpServlet {
    }

源码下载

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Zh1g9Q40-1642060823153)(http://47.107.171.232/easily-j/images/20190310/42196bfc-cd1a-44ca-8f9a-269fb1aa37bd.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pH5PLxi8-1642060823155)(http://47.107.171.232/easily-j/images/20190310/2556c8bc-60c3-457c-b7a9-cd25ccbd0f02.png)]

微信公众号

  相关解决方案