Heim  >  Artikel  >  Java  >  Wie Spring Boot Thymeleaf integriert

Wie Spring Boot Thymeleaf integriert

王林
王林nach vorne
2023-05-16 09:22:111279Durchsuche

Thymeleaf

Grundlegende Einführung

Spring Boot empfiehlt offiziell die Verwendung von Thymeleaf als Template-Engine. SpringBoot bietet eine Reihe von Standardkonfigurationen für Thymeleaf und einen View-Resolver für Thymeleaf. Sobald die Abhängigkeiten von Thymeleaf in das Projekt importiert werden, wird die entsprechende automatische Konfiguration (ThymeleafAutoConfiguration) automatisch wirksam, sodass Thymeleaf perfekt in Spring Boot integriert werden kann. Die Thymeleaf-Vorlagen-Engine kann perfekt mit HTML-Tags kombiniert werden, um das Backend-Rendering von Daten zu erleichtern. Thymeleaf unterstützt statische Effekte und dynamische Effekte Wenn keine dynamischen Daten vorhanden sind, werden statische Effekte angezeigt. Die Vorlagen-Engine dient dazu, die Benutzeroberfläche von Geschäftsdaten (Inhalten) zu trennen Die Template-Engine der Website generiert ein Standard-HTML-DokumentEs dient dazu, mithilfe der Template-Datei und der Daten einen HTML-Code über die Template-Engine zu generieren **Gemeinsame Template-Engines sind: jsp, freemarker, Velocity, Thymeleaf Der Standard-Schreibort von Thymeleaf befindet sich auf der offiziellen Website von templates Thymeleaf in diesem Verzeichnis: https://www.thymeleaf.org/

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Der Standardansichtspfad von Thymeleaf lautet: / resources/templates. Erstellen Sie HTML in diesem Verzeichnis und stellen Sie thymeleaf
<html lang="en" xmlns:th="http://www.thymleaf.org">

xmlns:th vor ="http://www.thymleaf.org“>

Grundlegende Syntax

${domain attribute name}: Rufen Sie den Domänenattributwert in der Anforderungsdomäne ab und zeigen Sie ihn an
${session.domain attribute name}: Holen Sie sich den Attributwert und die Anzeige der Domäne in der Sitzungsdomäne.

th: TexttextersetzungWie Spring Boot Thymeleaf integriert

< p th:text="${name}">aaa</p>

th:if und th:unless Textersetzung

Verwenden Sie die Attribute th:if und th:unless für die bedingte Beurteilung, th:unlessth:unless ist genau das Gegenteil, der Inhalt wird nur angezeigt, wenn die Ausdrucksbedingung nicht erfüllt ist
<span th:text="${user.name}">Tom</span>

thymeleaf verwendet standardmäßig den Variablennamen + Statistikstatus

Wenn die Statusvariable nicht explizit festgelegt ist, verwendet thymeleaf standardmäßig einen Variablennamen + Statistikstatus

Wie Spring Boot Thymeleaf integriert

<h3 th:if="${age>=18}">成年</h3>
<h3 th:unless="${age>=18}">未成年</h3>

th:id, th:value, th :checked usw. (bezogen auf das Formular)

th:object kann Objektattribute definieren*

{} kann in Verbindung mit th:object verwendet werden, um die Attribute im Objekt zu extrahieren

#dates.format () kann zum Formatieren des Datumsformats verwendet werden.


<html lang="en" xmlns:th="http://www.thymleaf.org">

    
    Title
    


    

学生管理系统

序号 姓名 年龄 性别 班级 生日 操作
1 aa 22 计科1班 2022-2-3 删除

Integrieren Sie Thymeleaf
Dann verwenden wir hier den Druid-Verbindungspool, also müssen wir ihn in die POM-Datei importieren. Relevante Abhängigkeiten

<!--http://localhost:8080/stu/10 -->
<a th:href="${&#39;/stus/&#39;+ stu.id}" rel="external nofollow" >编辑学生1</a>

<!--http://localhost:8080/stu?id=10 -->
<a th:href="@{/stus(id=${stu.id})}" rel="external nofollow" >编辑学生2</a>

<!--http://localhost:8080/stu?id=10&name=abc -->
<a th:href="@{/stus(id=${stu.id},name=${stu.name})}" rel="external nofollow" >编辑学生3</a>
Dann müssen wir relevante Konfigurationen in der globalen Konfigurationsdatei application.properties

<div th:switch="${stu.role}">
  <h3 th:case="banzhang">班长</h3>
  <h3 th:case="tuanzhishu">团支书</h3>
  <h3 th:case="${data}">学委</h3>
  <h3 th:case="*">其他</h3>
  
</div>

Datenbankvorbereitung vornehmen. Bereiten Sie die Entitätsklassen vor entsprechend den Tabellen in der Datenbank und der dreistufigen Struktur

<tr th:each="stu: ${stus}">
  <td th:text="${stuStat.index}"></td>
  <td th:text="${ stu.name}"></td>
  <td th:text="${ stu.age}"></td>    
</tr>

thymeleaf

 <form th:object="${stu}">
        编号:<input type="text" name="id" th:value="*{id}"><br>
        姓名:<input type="text" name="name" th:value="*{name}"><br>
        年龄:<input type="text" name="age" th:value="*{age}"><br>
        性别:<input type="radio" name="gender" value="true" th:checked="*{gender}">男<br>
        性别:<input type="radio" name="gender" value="true" th:checked="*{not gender}">女<br>
        生日:<input type="text" name="birth" th:value="*{#dates.format(birth,&#39;yyyy-MM-dd&#39;)}"><br>
        <input type="submit" value="编辑">
    </form>

Controller

 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.11</version>
        </dependency>

Dann bereiten wir zuerst die Seite vorWie Spring Boot Thymeleaf integriert

# 指定Mybatis的Mapper接口的xml映射文件的路径
mybatis.mapper-locations=classpath:mapper/*xml
# MySQL数据库驱动
#这个驱动也可以省略,可以根据使用的MySQL自动加载相应的驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=com.alibaba.druid.pool.DruidDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/school?serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
# 数据库用户名和密码
spring.datasource.username=root
spring.datasource.password=a87684009.
# 设置日志级别
logging.level.com.zyh.springboot=debug
# 开启mybatis驼峰命名规则自动转换功能
mybatis.configuration.map-underscore-to-camel-case=true


Wenn wir auf Löschen klicken, muss das Backend gelöscht werden die entsprechenden Daten aus der Datenbank auf Basis der id wurde vom Frontend übergeben. Hier werden wir es zunächst gemäß der bekannten Methode vervollständigen, die wir zuvor gelernt haben. Später werden wir ausführlich über die Front-End- und Back-End-Trennungsentwicklung sprechen

Löschvorgang

Controller (die vorherige Methode wird hier nicht eingefügt). , sonst gibt es zu viel Code)

@Data
public class Stu {
    private Integer id;
    private String name;
    private Integer age;
    private Boolean gender;
    private Integer cid;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birth;
}

ServiceWie Spring Boot Thymeleaf integriert

@Mapper
public interface StuMapper {
    /**
     * 查询所有学生信息
     * @return
     * @throws Exception
     */
    @Select("select * from stu")
     List<Stu> queryAllStu() throws Exception;
}

Wie Spring Boot Thymeleaf integriertService-Implementierungsklasse

public interface StuService  {
    /**
     * 查询所有学生信息
     * @return
     */
    List<Stu> queryAllStu() throws Exception;
}

Mapper

@Service
public class StuServiceImpl implements StuService {
    @Autowired
    private StuMapper stuMapper;
    @Override
    public List<Stu> queryAllStu() throws Exception {
         return stuMapper.queryAllStu();
    }
}

Löschen Sie die Daten mit der Nummer 8

Wie Spring Boot Thymeleaf integriert

编辑操作

页面stus.html

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .tb-stus{
            width: 900px;
            margin: 0 auto;
            border: black 1px solid;
            border-collapse: collapse;
        }
        .tb-stus th,td{
            padding: 10px;
            text-align: center;
            border:1px solid black;
        }
    </style>
</head>
<body>
<h3 align="center">学生管理系统</h3>
<table class="tb-stus">
    <thead>
    <tr>
        <th>序号</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>班级</th>
        <th>生日</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="stu,status: ${stuList}">
        <td th:text="${stu.id}">1</td>
        <td th:text="${stu.name}">aa</td>
        <td th:text="${stu.age}">22</td>
<!--        gender的属性值为1表示性别为男-->
        <td th:if="${stu.gender}">男</td>
        <td th:unless="${stu.gender}">女</td>
        <td th:text="${stu.cid}">计科1班</td>
         <td th:text="${#dates.format(stu.birth,&#39;yyyy-MM-dd&#39;)}">2022-2-3</td>
        <td>
<!--            localhost:8080/stu/delete/8-->
<!--            <a th:href="${&#39;/stu/delete/&#39;+stu.id}" rel="external nofollow"  rel="external nofollow" >删除</a>-->
            <!--http://localhost:8080/stu/delete?id=10-->
            <a th:href="@{/stu/delete(id=${stu.id})}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >删除</a>
            <a th:href="@{/stu/edit(id=${stu.id})}" rel="external nofollow"  rel="external nofollow" >编辑</a>
        </td>
    </tr>
    </tbody>
</table>

</body>
</html>

页面 stu-edit.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF-8">
    <title>编辑画面</title>
  </head>
  <body>
    <h3 >编辑学生信息</h3>
    <form action="" method="post" th:object="${stu}">
      学号:<input type="text" name="id" th:value="*{id}"  ><br><br>
      姓名:<input type="text" name="name"  th:value="*{name}"><br><br>
      年龄:<input type="text" name="age"  th:value="*{age}"><br><br>
      性别:<input type="radio" name="gender"    th:checked="*{gender}"  >男
      <input type="radio" name="gender"   th:checked="*{!gender}" >女<br><br>
      班级:<input type="text" name="cid" th:value="*{cid}"><br><br>
      生日:<input type="text" name="birth" th:value="*{#dates.format(birth,&#39;yyyy-MM-dd&#39;)}"><br><br>
      <input type="submit" value="编辑">
    </form>
  </body>
</html>

Controller

/**
     * 根据id来修改数据
     * 我们首先得先根据id把数据查询出来,然后把数据展示出来
     * 用户再进行编辑,用户编辑完并且提交以后,跳转到学生管理系统画面,展示所有数据
     * @return
     */
    @RequestMapping("/edit")
    public String edit(@RequestParam("id") Integer id,Model model){
        System.out.println("id"+id);
        try {
            Stu stu=stuService.queryById(id);
            model.addAttribute("stu",stu);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "stu-edit";
    }

Service

public interface StuService  {
    /**
     * 查询所有学生信息
     * @return
     */
    List<Stu> queryAllStu() throws Exception;

    /**
     * 根据id来删除学生信息
     * @param id
     * @throws Exception
     */
    void deleteByid(Integer id) throws Exception;

    /**
     * 根据id来查询对应学生信息
     * @param id
     * @return
     * @throws Exception
     */
    Stu queryById(Integer id) throws Exception;
}

Service实现类

@Service
public class StuServiceImpl implements StuService {
    @Autowired
    private StuMapper stuMapper;
    @Override
    public List<Stu> queryAllStu() throws Exception {
         return stuMapper.queryAllStu();
    }

    /**
     * 根据id删除数据
     * @param id
     */
    @Override
    public void deleteByid(Integer id) throws Exception {
        stuMapper.deleteById(id);
    }

    @Override
    public Stu queryById(Integer id) throws Exception {
        return stuMapper.queryById(id);
    }
}

Mapper

@Mapper
public interface StuMapper {
    /**
    * 查询所有学生信息
    * @return
    * @throws Exception
    */
    @Select("select * from stu")
    List<Stu> queryAllStu() throws Exception;
    @Delete("delete from stu where id=#{id}")
    void deleteById( Integer id);
    @Select("select * from stu where id=#{id}")
    Stu queryById(Integer id) throws Exception;
}

Wie Spring Boot Thymeleaf integriert

比如在序号为4中,点击编辑

Wie Spring Boot Thymeleaf integriert

用户登录

登录页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h3>用户登录</h3>
    <form action="/login" method="post">
        账号:<input type="text" name="username"><br><br>
        密码:<input type="password" name="password"><br><br>
        <input type="submit" value="登录">
    </form>


</body>
</html>

因为需要判断用户是否存在,这是从数据库进行查询的,所以要准备对应的管理员表

# 创建管理员表
CREATE TABLE admin(
	id INT PRIMARY KEY AUTO_INCREMENT,
	username VARCHAR(20),
	`password` VARCHAR(20)
); 

INSERT INTO admin VALUES
	(DEFAULT,&#39;aaa&#39;,111),
	(DEFAULT,&#39;bbb&#39;,222),
	(DEFAULT,&#39;ccc&#39;,333);
# 查询测试
SELECT * FROM admin;	

准备对应的实体类

@Data
public class Admin {
    private String username;
    private String password;
}

Controller

@Controller
@SessionAttributes(names = {"admin"})
public class AdminController {
    @Autowired
    private AdminService adminService;

    /**
     * 显示登录页面
     * @return
     */
    @RequestMapping(value = "/loginUi")
    public String loginUi(){
        return "login";
    }
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String username, String password, Model model){
        try {
            Admin admin = adminService.login(username, password);
            //用户名存在说明登录成功
            if (admin!=null){
                //存放到session域中
                model.addAttribute("admin",admin);
                return "redirect:/stu/stusUi";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/loginUi";
    }

}

Service

public interface AdminService {
    Admin login(String username,String password) throws Exception;
}

Service对应的实现类

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Override
    public Admin login(String username, String password) throws Exception {
        return adminMapper.queryByUsernameAndPassword(username,password);
    }
}

Mapper

@Mapper
public interface AdminMapper {
    @Select("select * from admin where username=#{username} and password=#{password}")
    Admin queryByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
}

Wie Spring Boot Thymeleaf integriert

Wie Spring Boot Thymeleaf integriert

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .tb-stus{
            width: 900px;
            margin: 0 auto;
            border: black 1px solid;
            border-collapse: collapse;
        }
        .tb-stus th,td{
            padding: 10px;
            text-align: center;
            border:1px solid black;
        }
    </style>
</head>
<body>
    <h3 align="center">学生管理系统</h3>
    <h3 th:if="${session.admin!=null}" th:text="${session.admin.username}">用户名</h3>
    <a th:unless="${session.admin!=null}" href="/loginUi" rel="external nofollow" >登录</a>
    <a th:if="${session.admin!=null}" href="/logout" rel="external nofollow" >注销用户</a>
<table class="tb-stus">
    <thead>
    <tr>
        <th>序号</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>班级</th>
        <th>生日</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="stu,status: ${stuList}">
        <td th:text="${stu.id}">1</td>
        <td th:text="${stu.name}">aa</td>
        <td th:text="${stu.age}">22</td>
<!--        gender的属性值为1表示性别为男-->
        <td th:if="${stu.gender}">男</td>
        <td th:unless="${stu.gender}">女</td>
        <td th:text="${stu.cid}">计科1班</td>
        <td th:text="${#dates.format(stu.birth,&#39;yyyy-MM-dd&#39;)}">2022-2-3</td>
        <td>
<!--            localhost:8080/stu/delete/8-->
<!--            <a th:href="${&#39;/stu/delete/&#39;+stu.id}" rel="external nofollow"  rel="external nofollow" >删除</a>-->
            <!--http://localhost:8080/stu/delete?id=10-->
            <a th:href="@{/stu/delete(id=${stu.id})}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >删除</a>
            <a th:href="@{/stu/edit(id=${stu.id})}" rel="external nofollow"  rel="external nofollow" >编辑</a>
        </td>
    </tr>
    </tbody>
</table>

</body>
</html>

Wie Spring Boot Thymeleaf integriert

Wie Spring Boot Thymeleaf integriert

Wie Spring Boot Thymeleaf integriert

用户注销

注销的话,我们把session域中的用户对象取消,然后这个时候就得重新登录,应该要跳转到登录画面

@RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("admin");
        return "redirect:/loginUi";
    }

Wie Spring Boot Thymeleaf integriert

点击注销用户

Wie Spring Boot Thymeleaf integriert

Das obige ist der detaillierte Inhalt vonWie Spring Boot Thymeleaf integriert. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:yisu.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen