Java中springboot搭建html的操作代码
作者:db_lsk_2043
最终效果图
前言:springboot是什么
Spring Boot简化了开发人员对Spring框架的应用程序的搭建和配置过程,提供了一套简单易用的开发工具和规范,使开发人员能够更专注于业务逻辑的开发,而无需过多关注繁琐的配置和细节。
一、实现类和接口类
在Book中设置图书的属性
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框架提供的一个接口,它提供了许多用于操作数据库的方法,例如保存数据、查询数据、删除数据等。通过继承JpaRepository接口,BookRepository就可以使用这些方法来对Book实体对象进行持久化操作。
并且设置了模糊查询。
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实现类
在BookServiceImpl中通过这些方法的实现,BookServiceImpl类成为了一个BookService接口的实现类,可以提供对书籍的保存、查询和删除等服务操作。
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){ //调用数据访问层查找指定ID的图书,返回Optional对象 Optional< Book > optional = bookRepository.findById(id); Book book = null; //如果存在指定id的图书 if (optional.isPresent()) { //从Optional对象中获取图书对象 book = optional.get(); } else { //否则抛出运行时异常 throw new RuntimeException(" :: " + id); } return book; } @Override public Page<Book> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) { //设置排序参数,升序ASC/降序DESC? Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).ascending() : Sort.by(sortField).descending(); //根据页号/每页记录数/排序依据返回某指定页面数据。 Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort); return this.bookRepository.findAll(pageable); } @Override public List<Book> QueryBook(String bookName) { //将查询结果返回 return bookRepository.findByNameContaining(bookName); } }
BookService接口
在BookService中通过定义这些方法,BookService接口提供了一系列操作图书的服务接口,具体的实现类可以根据需要来实现这些方法来提供对图书的具体操作功能。
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业务层
在BookController中,使用@Autowired注解将BookService注入到该类的booksService属性中。通过依赖注入,BookController可以使用BookService中定义的方法来处理业务逻辑。
@Autowired注解告诉Spring框架将BookService的实例自动注入到booksService属性中,这样在BookController中就可以直接使用booksService来调用BookService中定义的方法了。
这样,BookController就可以与视图层(如前端页面)进行交互
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:/"; } //获取分页数据 @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>图书管理系统</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" 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}}">价格</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搭建新增图书界面,通过添加的超链接进入界面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>添加图书</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> </head> <body> <div class="container"> <h1>图书管理系统</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="请输入图书的售价" 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搭建更新图书界面,通过添加的超链接进入界面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>更新图书</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> </head> <body> <div class="container"> <h1>图书管理系统</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="请输入图书的售价" 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中设置了超链接跳转到查询图书的界面中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>查询结果</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" 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> 价格 </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>
运行后的效果就出来了
到此这篇关于Java中springboot搭建html的文章就介绍到这了,更多相关springboot搭建html内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!