<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Spring Boot – CRUD 應用程序 > 原文: [https://howtodoinjava.com/spring-boot2/crud-application-thymeleaf/](https://howtodoinjava.com/spring-boot2/crud-application-thymeleaf/) 通過基于 [Thymeleaf](https://www.thymeleaf.org/) 和 spring mvc 支持的基于表單的 UI,學習構建支持 **CRUD** 操作的 [Spring Boot](https://howtodoinjava.com/spring-boot-tutorials/) Web 應用程序。 ## 1\. 概述 在本教程中,我們正在[創建具有兩個視圖的 Web 應用程序](https://howtodoinjava.com/maven/maven-web-project-in-eclipse/): * **列出所有員工視圖** – 以表格形式在 UI 中從數據庫顯示所有員工。 此外,還有指向“更新”或“刪除”任何員工的鏈接。 該界面還具有一個單獨的選項,可以導航到“創建”員工界面。 ![Spring boot hibernate thymeleaf example](https://img.kancloud.cn/7f/85/7f850e3ab4242d28b95bebd7fb86f06b_906x355.jpg) 列出所有員工的界面 * **創建/更新員工視圖** – 此界面用于添加新員工或編輯現有員工的詳細信息。 ![Add employee screen](https://img.kancloud.cn/47/13/47138eb91a2293ea593b2b651bfb514f_626x419.jpg) 添加員工的界面 此示例中有兩個主要組件需要重點關注-MVC 控制器和 UI 視圖。 ## 2\. Spring MVC 控制器 控制器類具有 URL 映射及其處理器方法。 所有 CRUD 操作都有處理器方法,包括 POST 操作,以處理表單提交以創建/更新員工的過程。 注意給定的處理器方法如何將模型數據綁定到視圖; 并且它們以字符串格式返回視圖名稱,該視圖名稱由 HTML 文件中的[視圖解析器](https://howtodoinjava.com/spring-boot/spring-boot-jsp-view-example/)解析。 `EmployeeMvcController.java` ```java import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; 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 org.springframework.web.bind.annotation.RequestMethod; import com.howtodoinjava.demo.entity.EmployeeEntity; import com.howtodoinjava.demo.exception.RecordNotFoundException; import com.howtodoinjava.demo.service.EmployeeService; @Controller @RequestMapping("/") public class EmployeeMvcController { @Autowired EmployeeService service; @RequestMapping public String getAllEmployees(Model model) { List<EmployeeEntity> list = service.getAllEmployees(); model.addAttribute("employees", list); return "list-employees"; } @RequestMapping(path = {"/edit", "/edit/{id}"}) public String editEmployeeById(Model model, @PathVariable("id") Optional<Long> id) throws RecordNotFoundException { if (id.isPresent()) { EmployeeEntity entity = service.getEmployeeById(id.get()); model.addAttribute("employee", entity); } else { model.addAttribute("employee", new EmployeeEntity()); } return "add-edit-employee"; } @RequestMapping(path = "/delete/{id}") public String deleteEmployeeById(Model model, @PathVariable("id") Long id) throws RecordNotFoundException { service.deleteEmployeeById(id); return "redirect:/"; } @RequestMapping(path = "/createEmployee", method = RequestMethod.POST) public String createOrUpdateEmployee(EmployeeEntity employee) { service.createOrUpdateEmployee(employee); return "redirect:/"; } } ``` * `getAllEmployees()` – 返回所有員工的列表,并映射到路徑`/`。 這是應用程序的默認視圖。 * `editEmployeeById()` – 用于添加新員工或編輯現有員工。 兩種操作都使用相同的 HTML 視圖。 如果上下文中有一個員工 ID,則將對該員工進行編輯-否則將創建一個新員工。 * `deleteEmployeeById()` – 通過 ID 刪除員工的簡單 URL 請求。 * `createOrUpdateEmployee()` – 此方法處理用于創建新雇員或更新雇員的 HTTP POST 請求。 創建或更新操作取決于模型中是否存在員工 ID。 ## 3\. Thymeleaf 模板 如前所述,我們在此示例中使用兩個視圖。 `list-employees.html` ```java <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>All Employees</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css"> </head> <body> <div class="container my-2"> <div class="card"> <div class="card-body"> <div th:switch="${employees}" class="container my-5"> <p class="my-5"> <a href="/edit" class="btn btn-primary"> <i class="fas fa-user-plus ml-2"> Add Employee </i></a> </p> <div class="col-md-10"> <h2 th:case="null">No record found !!</h2> <div th:case="*"> <table class="table table-striped table-responsive-md"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tbody> <tr th:each="employee : ${employees}"> <td th:text="${employee.firstName}"></td> <td th:text="${employee.lastName}"></td> <td th:text="${employee.email}"></td> <td> <a th:href="@{/edit/{id}(id=${employee.id})}" class="btn btn-primary"> <i class="fas fa-user-edit ml-2"></i> </a> </td> <td> <a th:href="@{/delete/{id}(id=${employee.id})}" class="btn btn-primary"> <i class="fas fa-user-times ml-2"></i> </a> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> </body> </html> ``` `add-edit-employee.html` ```java <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Add Employee</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css"> </head> <body> <div class="container my-5"> <h3> Add Employee</h3> <div class="card"> <div class="card-body"> <div class="col-md-10"> <form action="#" th:action="@{/createEmployee}" th:object="${employee}" method="post"> <div class="row"> <div class="form-group col-md-8"> <label for="name" class="col-form-label">First Name</label> <input type="text" th:field="*{firstName}" class="form-control" id="firstName" placeholder="First Name" /> </div> <div class="form-group col-md-8"> <label for="name" class="col-form-label">Last Name</label> <input type="text" th:field="*{lastName}" class="form-control" id="lastName" placeholder="Last Name" /> </div> <div class="form-group col-md-8"> <label for="email" class="col-form-label">Email</label> <input type="text" th:field="*{email}" class="form-control" id="email" placeholder="Email Id" /> </div> <div class="col-md-6"> <input type="submit" class="btn btn-primary" value=" Submit "> </div> <input type="hidden" id="id" th:field="*{id}"> </div> </form> </div> </div> </div> </div> </body> </html> ``` ## 4\. 實體和存儲庫 我們已經將`EmployeeEntity`類作為模型綁定到 UI。 `EmployeeEntity.java` ```java import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="TBL_EMPLOYEES") public class EmployeeEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name="first_name") private String firstName; @Column(name="last_name") private String lastName; @Column(name="email", nullable=false, length=200) private String email; //Setters and getters @Override public String toString() { return "EmployeeEntity [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]"; } } ``` 為了將數據持久存儲在數據庫中,我們使用[ H2(內存中)數據庫](https://howtodoinjava.com/spring-boot2/h2-database-example/),并使用 Spring 數據的`CrudRepository`接口。 它為簡單的 CRUD 操作提供了開箱即用的內置方法。 `EmployeeRepository.java` ```java import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.howtodoinjava.demo.entity.EmployeeEntity; @Repository public interface EmployeeRepository extends CrudRepository<EmployeeEntity, Long> { } ``` 請注意,使用兩個 SQL 文件初始化了存儲庫,這兩個 SQL 文件創建數據庫表并向其中填充默認數據。 `schema.sql` ```java DROP TABLE IF EXISTS TBL_EMPLOYEES; CREATE TABLE TBL_EMPLOYEES ( id INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(250) NOT NULL, last_name VARCHAR(250) NOT NULL, email VARCHAR(250) DEFAULT NULL ); ``` `data.sql` ```java INSERT INTO TBL_EMPLOYEES (first_name, last_name, email) VALUES ('Lokesh', 'Gupta', 'howtodoinjava@gmail.com'), ('John', 'Doe', 'xyz@email.com'); ``` ## 5\. 服務類 另一個重要的類是`EmployeeService`類,控制器通過該類與存儲庫進行交互。 它包含要執行的其他業務邏輯。 `EmployeeService.java` ```java import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.howtodoinjava.demo.entity.EmployeeEntity; import com.howtodoinjava.demo.exception.RecordNotFoundException; import com.howtodoinjava.demo.repository.EmployeeRepository; @Service public class EmployeeService { @Autowired EmployeeRepository repository; public List<EmployeeEntity> getAllEmployees() { List<EmployeeEntity> result = (List<EmployeeEntity>) repository.findAll(); if(result.size() > 0) { return result; } else { return new ArrayList<EmployeeEntity>(); } } public EmployeeEntity getEmployeeById(Long id) throws RecordNotFoundException { Optional<EmployeeEntity> employee = repository.findById(id); if(employee.isPresent()) { return employee.get(); } else { throw new RecordNotFoundException("No employee record exist for given id"); } } public EmployeeEntity createOrUpdateEmployee(EmployeeEntity entity) { if(entity.getId() == null) { entity = repository.save(entity); return entity; } else { Optional<EmployeeEntity> employee = repository.findById(entity.getId()); if(employee.isPresent()) { EmployeeEntity newEntity = employee.get(); newEntity.setEmail(entity.getEmail()); newEntity.setFirstName(entity.getFirstName()); newEntity.setLastName(entity.getLastName()); newEntity = repository.save(newEntity); return newEntity; } else { entity = repository.save(entity); return entity; } } } public void deleteEmployeeById(Long id) throws RecordNotFoundException { Optional<EmployeeEntity> employee = repository.findById(id); if(employee.isPresent()) { repository.deleteById(id); } else { throw new RecordNotFoundException("No employee record exist for given id"); } } } ``` ## 6\. 添加 Spring Boot 和 Thymeleaf Maven 依賴項 在 spring boot 項目中,我們只需要添加`spring-boot-starter-thymeleaf`依賴項,并使用默認配置為項目本身[自動配置](https://howtodoinjava.com/spring-boot/springbootapplication-auto-configuration/) thymeleaf。 它從`/src/main/resources/templates`文件夾中讀取 HTML 模板。 `pom.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.5.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>com.howtodoinjava</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project> ``` ## 7\. Spring Boot thymeleaf Crud 教程演示 以 Spring Boot 應用程序的形式啟動此應用程序,該應用程序將在嵌入式 tomcat 服務器中啟動 Web 應用程序。 **點擊網址:`http://localhost:8080/`** 驗證是否使用`data.sql`文件中的兩個默認員工詳細信息渲染了屏幕。 玩應用程序。 創建幾個新員工,編輯現有員工。 刪除一些員工。 如果在上述 **spring boot mvc 示例**中遇到任何錯誤,請告訴我。 [下載源碼](https://howtodoinjava.com/wp-content/downloads/spring-boot-hibernate-thymeleaf.zip) 學習愉快!
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看