【WEEK4】 【DAY3】Integrating SSM Framework: Modify and Delete Data 【English Version】

2024.3.20 Wednesday

Following the previous article 【WEEK4】 【DAY2】Integrating SSM Framework: Overview and Adding Data 【English Version】

7.6. Modify Functionality

7.6.1. Modify BookController.java

(The complete BookController.java code with delete functionality is located in 7.7.1.)

// Jump to the modify page
@RequestMapping("/toUpdate")
public String toUpdatePaper(int id,Model model){
    Books books = bookService.queryBookById(id);    // Return a book
    model.addAttribute("QBook",books);
    return "updateBook";
}

// Modify the book
@RequestMapping("updateBook")
public String updateBook(Books books){
    System.out.println("updateBook=>"+books);
    bookService.updateBook(books);
    return "redirect:/book/allBook";
}

7.6.2. Modify allBook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Book Display Page</title>
    <%--Beautify the page with Bootstrap--%>
    <%--Import online Bootstrap--%>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container"> <%--Container--%>

    <div class="row clearfix">  <%--Mark bar, clear float--%>
        <div class="col-md-12 column">
            <div class="page-header">   <!--Add space for content tagged as h1 (separate from other parts)-->
                <h1>
                    <small>Book List - Display All Books</small>
                </h1>
            </div>
        </div>

        <div class="row">
            <div class="col-md-4 column">
                <%--Should add a request -> processed by BookController.java--%>
                <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">Add New Book</a>
                <%--Create a button--%>
            </div>
        </div>

    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped"> <%--Darken the color when the mouse hovers over a row--%>
                <thead>
                    <tr>    <%--Table header--%>
                        <th>Book ID</th>
                        <th>Book Name</th>
                        <th>Book Count</th>
                        <th>Book Details</th>
                        <th>Operations</th>
                    </tr>
                </thead>

                <%--Books queried from the database, iterated from this list using foreach--%>
                <tbody>
                    <%--c:forEach will automatically import the tag (first line)--%>
                    <c:forEach var="book" items="${list}">
                        <tr>
                            <td>${book.bookID}</td>
                            <td>${book.bookName}</td>
                            <td>${book.bookCounts}</td>
                            <td>${book.detail}</td>
                            <td>    <%--Operations, &nbsp; for space. Want to see the original data when modifying, so need to first get the related data (here is passing the original book's id)--%>
                                <a href="${pageContext.request.contextPath}/book/toUpdate?id=${book.bookID}">Modify</a>
                                &nbsp; | &nbsp;
                                <%--“#” is used for placeholder, “Delete” appears on the page but without any functionality implemented--%>
                                <a href="#">Delete</a>
                            </td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </div>

</div>

</body>
</html>

7.6.3. Create New updateBook.jsp

Insert image description here

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Modify Book Information</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

<div class="container"> <%--Container--%>

    <div class="row clearfix">  <%--Mark bar, clear float--%>
        <div class="col-md-12 column">
            <div class="page-header">   <!--Add space for content tagged as h1 (separate from other parts)-->
                <h1>
                    <small>Modify Book</small>
                </h1>
            </div>
        </div>
    </div>
    <%--Book form--%>
    <form action="${pageContext.request.contextPath}/book/updateBook" method="post">
        <%--value after is the default value--%>
        <input type="hidden" name="bookID" value="${QBook.bookID}"/>    <%--This line controls the success of the modification, the frontend uses a hidden field to return the id--%>
        Book Name:<input type="text" name="bookName" value="${QBook.bookName}"/>
        Book Count:<input type="text" name="bookCounts" value="${QBook.bookCounts}"/>
        Book Details:<input type="text" name="detail" value="${QBook.detail}"/>
        <input type="submit" value="Modify"/>
    </form>

</div>

</body>
</html>

Hidden field
https://baike.baidu.com/item/hidden field/249616?fr=ge_ala
Reasons why MySQL doesn’t update after submitting a form on a JSP page
https://www.cnblogs.com/Meng2113/p/13511800.html

7.6.4. Modify MyBatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--Add the following three lines of configuration -> each operation will be explicitly printed on the server-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--Configure data source, delegated to Spring-->
    <typeAliases>
        <package name="P17.project"/>
    </typeAliases>

    <mappers>
        <!--If two files in the dao have different names, then use mapper resource-->
        <!--Any one of the following three lines is sufficient-->
        <mapper resource="P17/dao/BookDao.xml"/>
<!--        <mapper class="P17.dao.BookDao"/>-->
<!--        <package name="P17.dao"/>-->
    </mappers>
</configuration>

7.6.5. Running the Application

http://localhost:8080/SSMbuild_war_exploded/ (No change in the homepage)
http://localhost:8080/SSMbuild_war_exploded/book/allBook
Insert image description here
http://localhost:8080/SSMbuild_war_exploded/book/toUpdate?id=1
Insert image description here
Modified
http://localhost:8080/SSMbuild_war_exploded/book/allBook
Insert image description here

7.7. Deletion Function

7.7.1. Modify BookController.java

package P17.controller;

import P17.project.Books;
import P17.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.awt.print.Book;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
//controller calls service layer
    @Autowired
    @Qualifier("BookServiceImplement")
    private BookService bookService;

    //Query all books and return to a book display page
    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> list = bookService.queryAllBook();  //Call the business layer method to query all books
        model.addAttribute("list",list);    //Return query to frontend
        return "allBook";  //Return to allBook.jsp
    }

    //Redirect to add book page
    @RequestMapping("/toAddBook")
    public String toAddPaper(){
        return "addBook";
    }

    //Request to add book
    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println("addBook=>"+books);  //Log print
        bookService.addBook(books);
        return "redirect:/book/allBook";    //Redirect to @RequestMapping("/allBook") request
    }

    //Redirect to modify page
    @RequestMapping("/toUpdate")
    public String toUpdatePaper(int id,Model model){
        Books books = bookService.queryBookById(id);    //Return a book
        model.addAttribute("QBook",books);
        return "updateBook";
    }

    //Modify book
    @RequestMapping("updateBook")
    public String updateBook(Books books){
        System.out.println("updateBook=>"+books);
        bookService.updateBook(books);
        return "redirect:/book/allBook";
    }

    //Delete book using RestFul style
    @RequestMapping("/deleteBook/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }
}

/*
This is a general solution
    @RequestMapping("/deleteBook")
    public String deleteBook(int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }
 */

7.7.2. Modify allBook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Book Display Page</title>
    <%--Beautify page with BootStrap--%>
    <%--Import online BootStrap--%>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container"> <%--Container--%>

    <div class="row clearfix">  <%--Header row, clear floats--%>
        <div class="col-md-12 column">
            <div class="page-header">   <!--Adds space for h1 content (separate from other parts)-->
                <h1>
                    <small>Book List—Display All Books</small>
                </h1>
            </div>
        </div>

        <div class="row">
            <div class="col-md-4 column">
                <%--Should add a request->handled by BookController.java--%>
                <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">Add New Book</a>
                <%--Create a button--%>
            </div>
        </div>

    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped"> <%--Row color deepens when mouse hovers--%>
                <thead>
                    <tr>    <%--Table header--%>
                        <th>Book ID</th>
                        <th>Book Name</th>
                        <th>Book Quantity</th>
                        <th>Book Details</th>
                        <th>Operation</th>
                    </tr>
                </thead>

                <%--Books are queried from the database, looped out from this list using foreach--%>
                <tbody>
                    <%--c:forEach automatically imports tag (first line)--%>
                    <c:forEach var="book" items="${list}">
                        <tr>
                            <td>${book.bookID}</td>
                            <td>${book.bookName}</td>
                            <td>${book.bookCounts}</td>
                            <td>${book.detail}</td>
                            <td>    <%--Operations, &nbsp is for space. Modification wishes to see the original data, thus it needs to first get the related data (here is passing the original book's id)--%>
                                <a href="${pageContext.request.contextPath}/book/toUpdate?id=${book.bookID}">Modify</a>
                                &nbsp; | &nbsp;
                                <%--Delete--%>
                                <a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">Delete</a>
                            </td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </div>

</div>

</body>
</html>

7.7.3. Modify BookDao.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--One mapper corresponds to one interface-->
<mapper namespace="P17.dao.BookDao">

    <!--Add a book-->
    <insert id="addBook" parameterType="books">
#         ssmbuild.books refers to operating on the books table in the ssmbuild database
        INSERT INTO ssmbuild.books(bookName, bookCounts, detail)
        VALUES (#{bookName},#{bookCounts},#{detail});
    </insert>

    <!--Delete a book by id-->
    <!--This id is the specific method name in BookController where bookService.deleteBookById(id); is called, it cannot be wrong, otherwise, it reports error 500-->
    <delete id="deleteBookById" parameterType="int">
        DELETE FROM ssmbuild.books WHERE bookID = #{bookId}
    </delete>

    <!--Update Book-->
    <update id="updateBook" parameterType="Books">
        UPDATE ssmbuild.books
        SET bookName = #{bookName}, bookCounts = #{bookCounts}, detail = #{detail}
        WHERE bookID = #{bookID}
    </update>

    <!--Query by id, return a Book-->
    <select id="queryBookById" resultType="Books">
        SELECT * FROM ssmbuild.books
        WHERE bookID = #{bookId}
    </select>

    <!--Query all Books-->
    <select id="queryAllBook" resultType="Books">
        SELECT * FROM ssmbuild.books
    </select>

</mapper>

7.7.4. Execution

http://localhost:8080/SSMbuild_war_exploded/ (Homepage remains unchanged)
http://localhost:8080/SSMbuild_war_exploded/book/allBook
Insert image description here
After clicking “Delete” Insert image description here