📜  Spring Boot – Thymeleaf 示例

📅  最后修改于: 2022-05-13 01:55:07.246000             🧑  作者: Mango

Spring Boot – Thymeleaf 示例

Thymeleaf是一个基于 Java 的服务器端模板引擎,适用于 Web 和独立环境,能够处理 HTML、XML、JavaScript、CSS 甚至纯文本。它比 JPS 更强大,负责 UI 上的动态内容渲染。该引擎允许后端和前端开发人员在同一视图上并行工作。它可以直接访问Java对象和 spring bean 并将它们与 UI 绑定。当我们创建任何 Web 应用程序时,它主要与 Spring MVC 一起使用。因此,让我们从一个示例开始,了解 Thymeleaf 如何与 Spring 框架一起工作。

项目设置

在这里,我们将对 Employee 数据集执行 crud 操作。因此,为了构建它,我们必须添加某些以项目符号形式或也在 pom.xml 中列出的依赖项。

  • Spring Web (使用 Spring MVC 构建 Web,包括 RESTful 应用程序。使用 Apache Tomcat 作为默认嵌入式容器。)
  • Spring Data JPA (使用 Spring Data 和 Hibernate 使用Java Persistence API 在 SQL 存储中持久化数据。)
  • Spring Boot Devtools (提供快速应用程序重启、LiveReload 和配置以增强开发体验)
  • MySQL 驱动程序(MySQL JDBC 和 R2DBC 驱动程序)
  • Thymeleaf (用于 Web 和独立环境的服务器端Java模板引擎。允许 HTML 在浏览器中正确显示并作为静态原型。)

POM.XML

XML


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.2
         
    
    com.example
    thymeleaf
    0.0.1-SNAPSHOT
    thymeleaf
    Demo project for Spring Boot
    
        17
    
    
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        
  
        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
  
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


Java
package com.microservice.modal;
  
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
  
@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;
    private String name;
    private String email;
      
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}


Java
package com.microservice.service;
  
import java.util.List;
  
import com.microservice.modal.Employee;
  
public interface EmployeeServices {
    List getAllEmployee();
    void save(Employee employee);
    Employee getById(Long id);
    void deleteViaId(long id);
}


Java
package com.microservice.service;
  
import com.microservice.modal.Employee;
import com.microservice.repository.EmployeeRepository;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
  
@Service
public class EmployeeServiceImpl
    implements EmployeeServices {
    
    @Autowired private EmployeeRepository empRepo;
  
    @Override public List getAllEmployee()
    {
        return empRepo.findAll();
    }
  
    @Override public void save(Employee employee)
    {
        empRepo.save(employee);
    }
  
    @Override public Employee getById(Long id)
    {
        Optional optional = empRepo.findById(id);
        Employee employee = null;
        if (optional.isPresent())
            employee = optional.get();
        else
            throw new RuntimeException(
                "Employee not found for id : " + id);
        return employee;
    }
  
    @Override public void deleteViaId(long id)
    {
        empRepo.deleteById(id);
    }
}


Java
package com.microservice.repository;
  
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
  
import com.microservice.modal.Employee;
  
@Repository
public interface EmployeeRepository extends JpaRepository {
  
}


Java
package com.microservice.controller;
  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
  
import com.microservice.modal.Employee;
import com.microservice.service.EmployeeServiceImpl;
  
@Controller
public class EmployeeController {
  
    @Autowired
    private EmployeeServiceImpl employeeServiceImpl;
  
    @GetMapping("/")
    public String viewHomePage(Model model) {
        model.addAttribute("allemplist", employeeServiceImpl.getAllEmployee());
        return "index";
    }
  
    @GetMapping("/addnew")
    public String addNewEmployee(Model model) {
        Employee employee = new Employee();
        model.addAttribute("employee", employee);
        return "newemployee";
    }
  
    @PostMapping("/save")
    public String saveEmployee(@ModelAttribute("employee") Employee employee) {
        employeeServiceImpl.save(employee);
        return "redirect:/";
    }
  
    @GetMapping("/showFormForUpdate/{id}")
    public String updateForm(@PathVariable(value = "id") long id, Model model) {
        Employee employee = employeeServiceImpl.getById(id);
        model.addAttribute("employee", employee);
        return "update";
    }
  
    @GetMapping("/deleteEmployee/{id}")
    public String deleteThroughId(@PathVariable(value = "id") long id) {
        employeeServiceImpl.deleteViaId(id);
        return "redirect:/";
  
    }
}


HTML




Employee



  

Employee List

Add Employee                                                                         
NameEmailAction
Update                 Delete     


HTML




Employee Management System



    
        

Employee Management System

        
        

Save Employee

           
                                     
           
            Back to Employee List     


HTML




Employee Management System
  



    
        

Employee Management System

        
        

Update Employee

           
                                                                                                                                                                     
                   
                    Back to Employee List     


application.properties 文件

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/emp
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.properties.hibrenate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
logging.level.org.hibrenate.SQL=DEBUG
logging.level.org.hibrenate.type=TRACE

员工波乔

这是一个简单的 pojo 类,用于存储 Employee 的数据。

Java

package com.microservice.modal;
  
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
  
@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;
    private String name;
    private String email;
      
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

Employee Service 接口和 EmployeeServiceImpl 类

Java

package com.microservice.service;
  
import java.util.List;
  
import com.microservice.modal.Employee;
  
public interface EmployeeServices {
    List getAllEmployee();
    void save(Employee employee);
    Employee getById(Long id);
    void deleteViaId(long id);
}

实现 EmployeeSerivce 接口方法的 EmployeeServiceImpl 类

Java

package com.microservice.service;
  
import com.microservice.modal.Employee;
import com.microservice.repository.EmployeeRepository;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
  
@Service
public class EmployeeServiceImpl
    implements EmployeeServices {
    
    @Autowired private EmployeeRepository empRepo;
  
    @Override public List getAllEmployee()
    {
        return empRepo.findAll();
    }
  
    @Override public void save(Employee employee)
    {
        empRepo.save(employee);
    }
  
    @Override public Employee getById(Long id)
    {
        Optional optional = empRepo.findById(id);
        Employee employee = null;
        if (optional.isPresent())
            employee = optional.get();
        else
            throw new RuntimeException(
                "Employee not found for id : " + id);
        return employee;
    }
  
    @Override public void deleteViaId(long id)
    {
        empRepo.deleteById(id);
    }
}

EmployeeRepository 接口

在这里,我们使用 JPA 进行通信并将对象保存到数据库中。

Java

package com.microservice.repository;
  
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
  
import com.microservice.modal.Employee;
  
@Repository
public interface EmployeeRepository extends JpaRepository {
  
}

员工控制器类

这是控制器类,它基本上控制数据的流动。它控制数据流入模型对象并在数据更改时更新视图。所以在这里我们用 Thymeleaf 映射我们的对象数据。

  • 当用户在浏览器上键入 URL localhost:8080/时,请求转到viewHomePage()方法,在此方法中,我们获取员工列表并将其添加到带有键、值对的模式中并返回index.html页面。在 index.html 页面中,键(allemplist)被标识为Java对象,Thymeleaf 遍历列表并根据用户提供的模板生成动态内容。
  • /addNew –当用户点击添加员工按钮时,请求转到addNewEmployee()方法。在这个方法中,我们只需创建员工的空对象并将其发送回newemployee.html以便用户可以在这个空对象中填充数据,当用户点击保存按钮时, /save映射运行并获取对象员工并将该对象保存到数据库中。
  • /showFormForUpdate/{id} –此映射用于更新现有员工数据。
  • /deleteEmployee/{id} –此映射用于删除现有员工数据。

Java

package com.microservice.controller;
  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
  
import com.microservice.modal.Employee;
import com.microservice.service.EmployeeServiceImpl;
  
@Controller
public class EmployeeController {
  
    @Autowired
    private EmployeeServiceImpl employeeServiceImpl;
  
    @GetMapping("/")
    public String viewHomePage(Model model) {
        model.addAttribute("allemplist", employeeServiceImpl.getAllEmployee());
        return "index";
    }
  
    @GetMapping("/addnew")
    public String addNewEmployee(Model model) {
        Employee employee = new Employee();
        model.addAttribute("employee", employee);
        return "newemployee";
    }
  
    @PostMapping("/save")
    public String saveEmployee(@ModelAttribute("employee") Employee employee) {
        employeeServiceImpl.save(employee);
        return "redirect:/";
    }
  
    @GetMapping("/showFormForUpdate/{id}")
    public String updateForm(@PathVariable(value = "id") long id, Model model) {
        Employee employee = employeeServiceImpl.getById(id);
        model.addAttribute("employee", employee);
        return "update";
    }
  
    @GetMapping("/deleteEmployee/{id}")
    public String deleteThroughId(@PathVariable(value = "id") long id) {
        employeeServiceImpl.deleteViaId(id);
        return "redirect:/";
  
    }
}

索引.html

此页面用于显示员工列表。在这里,我们正在遍历控制器从viewHomePage()方法发送的allemplist 对象

HTML





Employee



  

Employee List

Add Employee                                                                         
NameEmailAction
Update                 Delete     

新雇员.html

此页面用于在数据库中添加新员工。在这里,我们只需在空字段中提供值并单击提交按钮。然后员工的数据转到saveEmployee()方法并将数据保存到数据库中。

HTML





Employee Management System



    
        

Employee Management System

        
        

Save Employee

           
                                     
           
            Back to Employee List     

更新.html

此页面用于更新现有员工的数据。

HTML





Employee Management System
  



    
        

Employee Management System

        
        

Update Employee

           
                                                                                                                                                                     
                   
                    Back to Employee List     

输出: