更新時(shí)間:2022-03-17 10:42:11 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1197次
大致流程是:
首先訪問到servlet層,在servlet層里調(diào)用StudentRepository的各個(gè)方法,然后展示到j(luò)sp頁面中。所以瀏覽器訪問路徑是servlet層里StudentServlet中@WebServlet("/student")的路徑(http://localhost:8080/student)
工具:idea,mysql數(shù)據(jù)庫
數(shù)據(jù)庫:
Student.java
public class Student {
private Integer id;
private String name;
private Integer numsex;
private Integer age;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNumsex() {
return numsex;
}
public void setNumsex(Integer numsex) {
this.numsex = numsex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Student(Integer id, String name, Integer numsex, Integer age, String password) {
this.id = id;
this.name = name;
this.numsex = numsex;
this.age = age;
this.password = password;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", numsex=" + numsex +
", age=" + age +
", password='" + password + '\'' +
'}';
}
StudentRepository:
import com.javaweb.entity.Student;
import com.javaweb.util.JDBCTools;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class StudentRepository {
public List<Student> findAll(){
List<Student> list=new ArrayList<>();
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try {
//調(diào)用JDBCTools連接mysql數(shù)據(jù)庫
connection= JDBCTools.getConnection();
String sql="select * from student";//查詢語句
preparedStatement=connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
//從resultSet拿出每個(gè)屬性數(shù)據(jù)
Integer id=resultSet.getInt(1);
String name=resultSet.getString(2);
Integer numsex=resultSet.getInt(3);
Integer age=resultSet.getInt(4);
String password=resultSet.getString(5);
//這里可以理解為,resultSet拿出每個(gè)屬性數(shù)據(jù)賦予student對(duì)象,形成一個(gè)有數(shù)據(jù)的student對(duì)象
Student student = new Student(id, name, numsex, age, password);
list.add(student);//可能多條數(shù)據(jù),放到集合中
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//調(diào)用JDBCTools,關(guān)閉connection,preparedStatement,resultSet
JDBCTools.release(connection,preparedStatement,resultSet);
}
return list;
}
//添加操作
public void add(Integer id,String name,Integer numsex,
Integer age,String password){
Connection connection=null;
PreparedStatement preparedStatement=null;
try {
connection= JDBCTools.getConnection();
String sql="insert into student(id,name,numsex,age,password) values (?,?,?,?,?)";
preparedStatement=connection.prepareStatement(sql);
//這里注意第一個(gè)參數(shù)對(duì)應(yīng)sql語句問號(hào)的序號(hào),
preparedStatement.setInt(1,id);//就是把id替代sql的第一個(gè)問號(hào),id由前端傳過來
preparedStatement.setString(2,name);
preparedStatement.setInt(3,numsex);
preparedStatement.setInt(4,age);
preparedStatement.setString(5,password);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCTools.release(connection,preparedStatement,null);
}
}
//刪除操作
public void deleteById(Integer id){
Connection connection=null;
PreparedStatement preparedStatement=null;
try {
connection= JDBCTools.getConnection();
String sql="delete from student where id=?";
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setInt(1,id);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCTools.release(connection,preparedStatement,null);
}
}
//根據(jù)id查詢
public Student findById(Integer id){
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
Student student=null;
try {
connection= JDBCTools.getConnection();
String sql="select * from student where id=?";
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setInt(1,id);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
Integer id2=resultSet.getInt(1);
String name=resultSet.getString(2);
Integer numsex=resultSet.getInt(3);
Integer age=resultSet.getInt(4);
String password=resultSet.getString(5);
student = new Student(id2, name, numsex, age, password);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCTools.release(connection,preparedStatement,resultSet);
}
return student;
}
//更新操作
public void update(Integer id,String name,Integer numsex,
Integer age,String password){
Connection connection=null;
PreparedStatement preparedStatement=null;
try {
connection= JDBCTools.getConnection();
String sql="update student set name=?,numsex=?,age=?,password=? where id=?";
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setString(1,name);
preparedStatement.setInt(2,numsex);
preparedStatement.setInt(3,age);
preparedStatement.setString(4,password);
preparedStatement.setInt(5,id);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCTools.release(connection,preparedStatement,null);
}
}
}
StudentServlet:
import com.javaweb.entity.Student;
import com.javaweb.repository.StudentRepository;
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.util.List;
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
//調(diào)用StudentRepository中的增刪改查方法
private StudentRepository studentRepository=new StudentRepository();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//判斷前端傳來的標(biāo)記,以此執(zhí)行相對(duì)應(yīng)的增刪改查操作
String method=req.getParameter("method");
if (method==null){
method="findAll";
}
switch (method){
case "findAll"://查詢所有數(shù)據(jù)
List<Student> list = studentRepository.findAll();//調(diào)用StudentRepository中的findAll()方法
req.setAttribute("list",list);//存入request中
req.getRequestDispatcher("index.jsp").forward(req,resp);//轉(zhuǎn)發(fā)到index.jsp中
case "delete"://刪除操作
String idStr=req.getParameter("id");
Integer id=Integer.parseInt(idStr);
studentRepository.deleteById(id);//根據(jù)id刪除
resp.sendRedirect("/student");
break;
case "findById":
idStr=req.getParameter("id");
id=Integer.parseInt(idStr);
req.setAttribute("student",studentRepository.findById(id));
req.getRequestDispatcher("update.jsp").forward(req,resp);
break;
case "add":
req.getRequestDispatcher("add.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");//防止中文亂碼
String method=req.getParameter("method");
switch (method){
case "add"://添加操作
//獲取前端傳來的數(shù)據(jù)
String idStr=req.getParameter("id");
String name=req.getParameter("name");
String numsexStr=req.getParameter("numsex");
String ageStr=req.getParameter("age");
String password=req.getParameter("password");
Integer id=Integer.parseInt(idStr);//轉(zhuǎn)化為整型
Integer numsex=Integer.parseInt(numsexStr);
Integer age=Integer.parseInt(ageStr);
studentRepository.add(id,name,numsex,age,password);//調(diào)用add方法
break;
case "update"://更新操作
idStr=req.getParameter("id");
name=req.getParameter("name");
numsexStr=req.getParameter("numsex");
ageStr=req.getParameter("age");
password=req.getParameter("password");
id=Integer.parseInt(idStr);
numsex=Integer.parseInt(numsexStr);
age=Integer.parseInt(ageStr);
studentRepository.update(id, name, numsex, age, password);
break;
}
resp.sendRedirect("/student");//重定向到index.jsp頁面
}
}
JDBCTools:
import java.sql.*;
public class JDBCTools {
private static Connection connection;
private static String url="jdbc:mysql://localhost:3306/he?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT";
private static String user="root";//用戶名
private static String pass="123z";//密碼
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
try {
connection= DriverManager.getConnection(url,user,pass);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void release(Connection connection, Statement statement, ResultSet resultSet){
try {
if (connection!=null) {
connection.close();
}
if (statement!=null){
statement.close();
}
if (resultSet!=null){
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
其中,web.xml創(chuàng)建之后不曾配置過,所以不貼代碼了
add.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/student" method="post">
編號(hào): <input type="text" name="id"/><br/>
姓名:<input type="text" name="name"/><br/>
性別:<input type="text" name="numsex"/><br/>
年齡:<input type="text" name="age"/><br/>
密碼:<input type="password" name="password"/><br/>
<input type="hidden" name="method" value="add"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1>學(xué)生管理系統(tǒng)</h1>
<div ><a href="/student?method=add">添加</a></div>
<table>
<tr>
<th>編號(hào)</th>
<th>姓名</th>
<th>性別</th>
<th>年齡</th>
<th>密碼</th>
<th>操作</th>
</tr>
<c:forEach items="${list}" var="student">
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.numsex}</td>
<td>${student.age}</td>
<td>${student.password}</td>
<td>
<a href="/student?method=delete&id=${student.id}">刪除</a>
<a href="/student?method=findById&id=${student.id}">修改</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
update.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/student" method="post">
編號(hào): <input type="text" name="id" value="${student.id}" readonly/><br/>
姓名:<input type="text" name="name" value="${student.name}"/><br/>
性別:<input type="text" name="numsex" value="${student.numsex}"/><br/>
年齡:<input type="text" name="age" value="${student.age}"/><br/>
密碼:<input type="password" name="password" value="${student.password}"/><br/>
<input type="hidden" name="method" value="update"/>
<input type="submit" value="修改"/>
</form>
</body>
</html>
注意訪問的路徑,我的是http://localhost:8080/student,student這個(gè)名字對(duì)應(yīng)servlet層里@WebServlet("/student")的路徑名
訪問的首頁:
這里就可以進(jìn)行對(duì)應(yīng)的增刪改操作了
點(diǎn)擊添加:會(huì)跳轉(zhuǎn)到添加頁面:
提交成功后自動(dòng)跳轉(zhuǎn)到首頁并展示
點(diǎn)擊刪除:數(shù)據(jù)直接刪掉,數(shù)據(jù)庫也同步刪掉了
點(diǎn)擊修改:跳轉(zhuǎn)到修改頁面,其中id設(shè)置不能修改:
提交后自動(dòng)返回首頁:
修改成功,同時(shí)數(shù)據(jù)庫也修改成功!
通過上述介紹,相信大家對(duì)JavaWeb增刪改查的基本操作已經(jīng)有所了解,大家如果對(duì)此比較感興趣,想了解更多相關(guān)知識(shí),不妨來關(guān)注一下動(dòng)力節(jié)點(diǎn)的JavaWeb學(xué)習(xí)視頻,里面還有更豐富的知識(shí)等著大家去學(xué)習(xí),希望對(duì)大家能夠有所幫助。
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743