您好,登錄后才能下訂單哦!
這篇文章主要介紹了JavaWeb增刪改查的基本操作是什么的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇JavaWeb增刪改查的基本操作是什么文章都會有所收獲,下面我們一起來看看吧。
大致流程是:
首先訪問到servlet層,在servlet層里調用StudentRepository的各個方法,然后展示到jsp頁面中。所以瀏覽器訪問路徑是servlet層里StudentServlet中@WebServlet("/student")的路徑(http://localhost:8080/student)
工具:idea,mysql數據庫
數據庫:
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 { //調用JDBCTools連接mysql數據庫 connection= JDBCTools.getConnection(); String sql="select * from student";//查詢語句 preparedStatement=connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); while (resultSet.next()){ //從resultSet拿出每個屬性數據 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拿出每個屬性數據賦予student對象,形成一個有數據的student對象 Student student = new Student(id, name, numsex, age, password); list.add(student);//可能多條數據,放到集合中 } } catch (SQLException e) { e.printStackTrace(); } finally { //調用JDBCTools,關閉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); //這里注意第一個參數對應sql語句問號的序號, preparedStatement.setInt(1,id);//就是把id替代sql的第一個問號,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); } } //根據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 { //調用StudentRepository中的增刪改查方法 private StudentRepository studentRepository=new StudentRepository(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //判斷前端傳來的標記,以此執行相對應的增刪改查操作 String method=req.getParameter("method"); if (method==null){ method="findAll"; } switch (method){ case "findAll"://查詢所有數據 List<Student> list = studentRepository.findAll();//調用StudentRepository中的findAll()方法 req.setAttribute("list",list);//存入request中 req.getRequestDispatcher("index.jsp").forward(req,resp);//轉發到index.jsp中 case "delete"://刪除操作 String idStr=req.getParameter("id"); Integer id=Integer.parseInt(idStr); studentRepository.deleteById(id);//根據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"://添加操作 //獲取前端傳來的數據 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);//轉化為整型 Integer numsex=Integer.parseInt(numsexStr); Integer age=Integer.parseInt(ageStr); studentRepository.add(id,name,numsex,age,password);//調用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創建之后不曾配置過,所以不貼代碼了
add.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> <title>Title</title></head><body><form action="/student" method="post"> 編號: <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>學生管理系統</h1> <div ><a href="/student?method=add">添加</a></div> <table> <tr> <th>編號</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"> 編號: <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這個名字對應servlet層里@WebServlet("/student")的路徑名
訪問的首頁:
這里就可以進行對應的增刪改操作了
點擊添加:會跳轉到添加頁面:
提交成功后自動跳轉到首頁并展示
點擊刪除:數據直接刪掉,數據庫也同步刪掉了
點擊修改:跳轉到修改頁面,其中id設置不能修改:
提交后自動返回首頁:
修改成功,同時數據庫也修改成功!
關于“JavaWeb增刪改查的基本操作是什么”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“JavaWeb增刪改查的基本操作是什么”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。