Java中springboot搭建html的操作代碼
最終效果圖
前言:springboot是什么
Spring Boot簡化了開發(fā)人員對Spring框架的應(yīng)用程序的搭建和配置過程,提供了一套簡單易用的開發(fā)工具和規(guī)范,使開發(fā)人員能夠更專注于業(yè)務(wù)邏輯的開發(fā),而無需過多關(guān)注繁瑣的配置和細(xì)節(jié)。
一、實(shí)現(xiàn)類和接口類
在Book中設(shè)置圖書的屬性
package com.lzzy.project.model; import jakarta.persistence.*; import lombok.Data; @Data @Entity @Table(name = "book") public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "name") private String name; @Column(name = "writer") private String writer; @Column(name = "state") private String state; @Column(name = "price") private int price; }
BookRepository接口
JpaRepository是Spring Data JPA框架提供的一個(gè)接口,它提供了許多用于操作數(shù)據(jù)庫的方法,例如保存數(shù)據(jù)、查詢數(shù)據(jù)、刪除數(shù)據(jù)等。通過繼承JpaRepository接口,BookRepository就可以使用這些方法來對Book實(shí)體對象進(jìn)行持久化操作。
并且設(shè)置了模糊查詢。
package com.lzzy.project.repository; import com.lzzy.project.model.Book; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface BookRepository extends JpaRepository<Book, Long> { @Query("SELECT b FROM Book b WHERE b.name LIKE %:keyword%") List<Book> findByNameContaining(@Param("keyword") String keyword); }
BookServiceImpl實(shí)現(xiàn)類
在BookServiceImpl中通過這些方法的實(shí)現(xiàn),BookServiceImpl類成為了一個(gè)BookService接口的實(shí)現(xiàn)類,可以提供對書籍的保存、查詢和刪除等服務(wù)操作。
package com.lzzy.project.service; import com.lzzy.project.model.Book; import com.lzzy.project.repository.BookRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class BookServiceImpl implements BookService { @Autowired private BookRepository bookRepository; @Override public void saveBook(Book book) {this.bookRepository.save(book);} @Override public List<Book> getAllBook() {return bookRepository.findAll();} @Override public void deleteBookById(long id) {this.bookRepository.deleteById(id);} //獲取指定圖書的id @Override public Book getBookById(long id){ //調(diào)用數(shù)據(jù)訪問層查找指定ID的圖書,返回Optional對象 Optional< Book > optional = bookRepository.findById(id); Book book = null; //如果存在指定id的圖書 if (optional.isPresent()) { //從Optional對象中獲取圖書對象 book = optional.get(); } else { //否則拋出運(yùn)行時(shí)異常 throw new RuntimeException(" :: " + id); } return book; } @Override public Page<Book> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) { //設(shè)置排序參數(shù),升序ASC/降序DESC? Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).ascending() : Sort.by(sortField).descending(); //根據(jù)頁號(hào)/每頁記錄數(shù)/排序依據(jù)返回某指定頁面數(shù)據(jù)。 Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort); return this.bookRepository.findAll(pageable); } @Override public List<Book> QueryBook(String bookName) { //將查詢結(jié)果返回 return bookRepository.findByNameContaining(bookName); } }
BookService接口
在BookService中通過定義這些方法,BookService接口提供了一系列操作圖書的服務(wù)接口,具體的實(shí)現(xiàn)類可以根據(jù)需要來實(shí)現(xiàn)這些方法來提供對圖書的具體操作功能。
package com.lzzy.project.service; import com.lzzy.project.model.Book; import org.springframework.data.domain.Page; import java.util.List; public interface BookService { //獲取所有的圖書 List<Book> getAllBook(); //新增/更新一本圖書 void saveBook(Book book); //刪除指定id的圖書 void deleteBookById(long id); //獲取指定圖書的id Book getBookById(long id); //分頁 + 排序 Page<Book> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection); // 按名稱查詢 List<Book> QueryBook(String bookName); }
BookController業(yè)務(wù)層
在BookController中,使用@Autowired注解將BookService注入到該類的booksService屬性中。通過依賴注入,BookController可以使用BookService中定義的方法來處理業(yè)務(wù)邏輯。
@Autowired注解告訴Spring框架將BookService的實(shí)例自動(dòng)注入到booksService屬性中,這樣在BookController中就可以直接使用booksService來調(diào)用BookService中定義的方法了。
這樣,BookController就可以與視圖層(如前端頁面)進(jìn)行交互
package com.lzzy.project.controller; import com.lzzy.project.model.Book; import com.lzzy.project.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller public class BookController { @Autowired private BookService booksService; // @GetMapping("/") // public String viewHomePage(Model model) { // model.addAttribute("listBook", booksService.getAllBook()); // return "index"; // } @GetMapping("/") public String viewHomePage(Model model) { return findPaginated(1, "id", "asc", model); } //新增圖書 @GetMapping("/showNewBookForm") public String showNewBookForm(Model model) { Book book = new Book(); model.addAttribute("book", book); return "add_book"; } //保存圖書 @PostMapping("/saveBook") public String saveBook(@ModelAttribute("book") Book book) { booksService.saveBook(book); return "redirect:/"; } //更新圖書 @GetMapping("/showFormForUpdate/{id}") public String showFormForUpdate(@PathVariable(value = "id") long id, Model model) { Book book = booksService.getBookById(id); model.addAttribute("book", book); return "update_book"; } //刪除圖書 @GetMapping("/deleteBook/{id}") public String deleteEmployee(@PathVariable(value = "id") long id) { this.booksService.deleteBookById(id); return "redirect:/"; } //獲取分頁數(shù)據(jù) @GetMapping("/page/{pageNo}") public String findPaginated(@PathVariable (value = "pageNo") int pageNo, @RequestParam("sortField") String sortField, @RequestParam("sortDir") String sortDir, Model model) { int pageSize = 5; Page<Book> page = booksService.findPaginated(pageNo, pageSize, sortField, sortDir); List<Book> listBook = page.getContent(); model.addAttribute("currentPage", pageNo); model.addAttribute("totalPages", page.getTotalPages()); model.addAttribute("totalItems", page.getTotalElements()); model.addAttribute("sortField", sortField); model.addAttribute("sortDir", sortDir); model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc"); model.addAttribute("listBook", listBook); return "index"; } //按書名查詢 @GetMapping("/query") public String queryBookName(@RequestParam("bookName") String bookName, Model model){ List<Book> books = booksService.QueryBook(bookName); model.addAttribute("books", books); return "query_book"; } }
二、html搭建
連接MySQL
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 spring.datasource.username= root spring.datasource.password= 123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # for Spring Boot 2 # spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect # for Spring Boot 3 spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQLDialect # Hibernate ddl auto (create, create-drop, validate, update) spring.jpa.hibernate.ddl-auto= update #?????hibernate-sql logging.level.org.hibernate.SQL=DEBUG logging.level.org.hibernate.type=TRACE
index.html 搭建基本框架
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>圖書管理系統(tǒng)</title> <link rel="stylesheet" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> </head> <body class="table-warning"> <div class="container my-2"> <h1 class="display-4 font-weight-bold text-center">Book List</h1> <div class="container"> <div class="row"> <div class="col-4"> <a th:href="@{/showNewBookForm}" class="btn btn-primary btn mb-3">添加圖書</a> </div> <div class="col-8"> <form class="form-inline justify-content-end" th:action="@{/query}"> <div class="form-group mr-2"> <input type="text" class="form-control" id="searchInput" name="bookName" placeholder="請輸入書名..."> </div> <button type="submit" class="btn btn-primary">搜索</button> </form> </div> </div> </div> <table border="1" class="table table-striped table-responsive-md table-danger"> <thead class="thead-dark"> <tr> <th> <a th:href="@{'/page/' + ${currentPage} + '?sortField=id&sortDir=' + ${reverseSortDir}}">圖書id</a> </th> <th> <a th:href="@{'/page/' + ${currentPage} + '?sortField=name&sortDir=' + ${reverseSortDir}}">書名</a> </th> <th> <a th:href="@{'/page/' + ${currentPage} + '?sortField=writer&sortDir=' + ${reverseSortDir}}">作者</a> </th> <th> <a th:href="@{'/page/' + ${currentPage} + '?sortField=state&sortDir=' + ${reverseSortDir}}">國家</a> </th> <th> <a th:href="@{'/page/' + ${currentPage} + '?sortField=price&sortDir=' + ${reverseSortDir}}">價(jià)格</a> </th> <th class="text-primary">操作</th> </tr> </thead> <tbody> <tr th:each="book : ${listBook}"> <td th:text="${book.id}"></td> <td th:text="${book.name}"></td> <td th:text="${book.writer}"></td> <td th:text="${book.state}"></td> <td th:text="${book.price}"></td> <td> <a th:href="@{/showFormForUpdate/{id}(id=${book.id})}" class="btn btn-primary btn-sm">更新圖書</a> <a th:href="@{/deleteBook/{id}(id=${book.id})}" class="btn btn-danger btn-sm">刪除</a> </td> </tr> </tbody> </table> <div th:if="${totalPages > 1}"> <div class="row col-sm-10"> <div class="col-sm-3"> Total Rows: [[${totalItems}]] </div> <div class="col-sm-5"> <span th:each="i: ${#numbers.sequence(1, totalPages)}"> <a th:if="${currentPage != i}" th:href="@{'/page/' + ${i}+ '?sortField=' + ${sortField} + '&sortDir=' + ${sortDir}}">[[${i}]]</a> <span th:unless="${currentPage != i}">[[${i}]]</span> </span> </div> <div class="col-sm-1"> <a th:if="${currentPage < totalPages}" th:href="@{'/page/' + ${currentPage + 1}+ '?sortField=' + ${sortField} + '&sortDir=' + ${sortDir}}"1 class="btn btn-primary">上一頁</a> <span th:unless="${currentPage < totalPages}" class="btn btn-primary disabled">上一頁</span> </div> <div class="col-sm-1"> <a th:if="${currentPage < totalPages}" th:href="@{'/page/' + ${totalPages}+ '?sortField=' + ${sortField} + '&sortDir=' + ${sortDir}}" class="btn btn-primary">下一頁</a> <span th:unless="${currentPage < totalPages}" class="btn btn-primary disabled">下一頁</span> </div> </div> </div> </div> </body> </html>
add_book.html搭建新增圖書界面,通過添加的超鏈接進(jìn)入界面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>添加圖書</title> <link rel="stylesheet" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> </head> <body> <div class="container"> <h1>圖書管理系統(tǒng)</h1> <hr> <h2>新增圖書</h2> <form action="#" th:action="@{/saveBook}" th:object="${book}" method="POST"> <input type="text" th:field="*{name}" placeholder="請輸入圖書名稱" class="form-control mb-4 col-4"> <input type="text" th:field="*{writer}" placeholder="請輸入作者" class="form-control mb-4 col-4"> <input type="text" th:field="*{state}" placeholder="請輸入作者的國家" class="form-control mb-4 col-4"> <input type="text" th:field="*{price}" placeholder="請輸入圖書的售價(jià)" class="form-control mb-4 col-4"> <button type="submit" class="btn btn-info col-2"> 添加 </button> </form> <hr> <a th:href="@{/}"> 返回圖書列表 </a> </div> </body> </html>
updata_book.html搭建更新圖書界面,通過添加的超鏈接進(jìn)入界面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>更新圖書</title> <link rel="stylesheet" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> </head> <body> <div class="container"> <h1>圖書管理系統(tǒng)</h1> <hr> <h2>更新圖書</h2> <form action="#" th:action="@{/saveBook}" th:object="${book}" method="POST"> <!--隱藏表單--> <input type="hidden" th:field="*{id}" /> <input type="text" th:field="*{name}" placeholder="請輸入圖書名稱" class="form-control mb-4 col-4"> <input type="text" th:field="*{writer}" placeholder="請輸入作者" class="form-control mb-4 col-4"> <input type="text" th:field="*{state}" placeholder="請輸入作者的國家" class="form-control mb-4 col-4"> <input type="text" th:field="*{price}" placeholder="請輸入圖書的售價(jià)" class="form-control mb-4 col-4"> <button type="submit" class="btn btn-info col-2"> 更新圖書 </button> </form> <hr> <a th:href="@{/}"> 返回圖書列表 </a> </div> </body> </html>
query_book.html中設(shè)置了超鏈接跳轉(zhuǎn)到查詢圖書的界面中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>查詢結(jié)果</title> <link rel="stylesheet" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> </head> <body> <div class="container my-2"> <h1 class="display-4 font-weight-bold text-center">Book List</h1> <div class="container"> <div class="row"> <div class="col-4"> <a th:href="@{/showNewBookForm}" class="btn btn-primary btn mb-3">添加圖書</a> </div> <div class="col-8"> <form class="form-inline justify-content-end"> <div class="form-group mr-2"> <input type="text" class="form-control" id="searchInput" placeholder="搜索"> </div> <button type="submit" class="btn btn-primary">搜索</button> </form> </div> </div> </div> <table border="1" class="table table-striped table-responsive-md"> <thead class="thead-dark"> <tr> <th> 圖書id </th> <th> 書名 </th> <th> 作者 </th> <th> 國家 </th> <th> 價(jià)格 </th> <th>操作</th> </tr> </thead> <tbody> <tr th:each="book : ${books}"> <td th:text="${book.id}"></td> <td th:text="${book.name}"></td> <td th:text="${book.writer}"></td> <td th:text="${book.state}"></td> <td th:text="${book.price}"></td> <td> <a th:href="@{/showFormForUpdate/{id}(id=${book.id})}" class="btn btn-primary btn-sm">更新圖書</a> <a th:href="@{/deleteBook/{id}(id=${book.id})}" class="btn btn-danger btn-sm">刪除</a> </td> </tr> </tbody> </table> <a th:href="@{/}"> 返回圖書列表 </a> </div> </body> </html>
運(yùn)行后的效果就出來了
到此這篇關(guān)于Java中springboot搭建html的文章就介紹到這了,更多相關(guān)springboot搭建html內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java中CompletableFuture異步執(zhí)行方法
本文主要介紹了java中CompletableFuture異步執(zhí)行方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06@Bean注解和@Configuration、@Component注解組合使用的區(qū)別
這篇文章主要介紹了@Bean注解和@Configuration、@Component注解組合使用的區(qū)別,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11SpringBoot?容器刷新前回調(diào)ApplicationContextInitializer
這篇文章主要為大家介紹了SpringBoot?容器刷新前回調(diào)ApplicationContextInitializer使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12Spring?Cloud?Eureka服務(wù)注冊中心入門流程分析
這篇文章主要介紹了Spring?Cloud?Eureka服務(wù)注冊中心入門流程分析,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06Java基于直方圖應(yīng)用的相似圖片識(shí)別實(shí)例
這篇文章主要介紹了Java基于直方圖應(yīng)用的相似圖片識(shí)別實(shí)例,是非常實(shí)用的技巧,多見于圖形里游戲中,需要的朋友可以參考下2014-09-09MybatisPlus中插入數(shù)據(jù)后獲取該對象主鍵值的實(shí)現(xiàn)
這篇文章主要介紹了MybatisPlus中插入數(shù)據(jù)后獲取該對象主鍵值,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09mybatisplus的坑?insert標(biāo)簽insert?into?select無參數(shù)問題的解決
這篇文章主要介紹了mybatisplus的坑?insert標(biāo)簽insert?into?select無參數(shù)問題的解決,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12SpringBoot中注解@ConfigurationProperties與@Value的區(qū)別與使用詳解
本文主要介紹了SpringBoot中注解@ConfigurationProperties與@Value的區(qū)別與使用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09