溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

JavaWeb增刪改查的基本操作是什么

發(fā)布時間:2022-09-26 13:52:16 來源:億速云 閱讀:187 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了JavaWeb增刪改查的基本操作是什么的相關(guān)知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇JavaWeb增刪改查的基本操作是什么文章都會有所收獲,下面我們一起來看看吧。

大致流程是:

首先訪問到servlet層,在servlet層里調(diào)用StudentRepository的各個方法,然后展示到j(luò)sp頁面中。所以瀏覽器訪問路徑是servlet層里StudentServlet中@WebServlet("/student")的路徑(http://localhost:8080/student)

工具:idea,mysql數(shù)據(jù)庫

1.首先看一下我的基本目錄:

JavaWeb增刪改查的基本操作是什么

數(shù)據(jù)庫:

JavaWeb增刪改查的基本操作是什么

2.各個層的代碼:

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拿出每個屬性數(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拿出每個屬性數(shù)據(jù)賦予student對象,形成一個有數(shù)據(jù)的student對象
                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);            //這里注意第一個參數(shù)對應(yīng)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);
        }
    }    //根據(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 {        //判斷前端傳來的標記,以此執(zhí)行相對應(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">
    編號: <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>編號</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>

3.瀏覽器訪問:

注意訪問的路徑,我的是http://localhost:8080/student,student這個名字對應(yīng)servlet層里@WebServlet("/student")的路徑名

訪問的首頁:

JavaWeb增刪改查的基本操作是什么

這里就可以進行對應(yīng)的增刪改操作了

點擊添加:會跳轉(zhuǎn)到添加頁面:

JavaWeb增刪改查的基本操作是什么

提交成功后自動跳轉(zhuǎn)到首頁并展示

點擊刪除:數(shù)據(jù)直接刪掉,數(shù)據(jù)庫也同步刪掉了

點擊修改:跳轉(zhuǎn)到修改頁面,其中id設(shè)置不能修改:

JavaWeb增刪改查的基本操作是什么

提交后自動返回首頁:

JavaWeb增刪改查的基本操作是什么

修改成功,同時數(shù)據(jù)庫也修改成功!

JavaWeb增刪改查的基本操作是什么

關(guān)于“JavaWeb增刪改查的基本操作是什么”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“JavaWeb增刪改查的基本操作是什么”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI