> Java > java지도 시간 > 본문

SpringBoot Thymeleaf 템플릿 엔진 예제 분석

WBOY
풀어 주다: 2023-05-12 17:28:06
앞으로
1316명이 탐색했습니다.

Jsp는 최초의 템플릿 기술로 뷰 레이어를 처리하는 데 사용되며 데이터 표시 템플릿에 사용됩니다

SpringBoot Thymeleaf 템플릿 엔진 예제 분석

B S 구조:

B: 브라우저: 데이터 표시, 요청 보내기, 처리 기능 없음

보내기 a.jsp에 접근을 요청하면 A.jsp는 서버 측에서 서블릿이 되고, 출력 데이터를 브라우저에 반환하면, jsp는 최종적으로 HTML 페이지로 변환됩니다

Template 기술을 사용하면 됩니다. 예를 들어 문자열 대체라고 생각하세요. 여기에 {data} 문자열이 있고 이를 고정 값이나 다른 값으로 바꾸지만 이 대체에는 템플릿 기술을 통해 뷰 레이어를 처리하는 몇 가지 추가 기능이 있습니다.

첫 번째 예:

SpringBoot Thymeleaf 템플릿 엔진 예제 분석

pom.xml: Thymeleaf 종속성:

<?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 https://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.7.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.bjpowernode</groupId>
    <artifactId>027-thymeleaf-first</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--模板引擎起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--web起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
로그인 후 복사
SpringBoot Thymeleaf 템플릿 엔진 예제 분석Create Controller: HelloThymeleafController:

package com.bjpowernode.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
public class HelloThymeleafController {
    @RequestMapping("/hello")
    public String helloThymeleaf(HttpServletRequest request){
        //添加数据到request作用域,模板引擎可以从request中获取数据
        request.setAttribute("data","欢迎使用Thymeleaf模板引擎");
        //指定视图 模板引擎使用的页面(html)
        //逻辑名称
        return "hello";
    }
}
로그인 후 복사

templates: 템플릿에 사용되는 뷰 파일을 배치하는 데 사용, 템플릿 엔진에서 사용하는 템플릿은 템플릿 아래에 배치됩니다. 디렉토리:

Create hello.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello html</title>
</head>
<body>
   <h4>使用Thymeleaf的例子</h4>
   <!--使用模板th:text=""获取数据-->
   <p th:text="${data}">想显示数据</p>
</body>
</html>
로그인 후 복사

메인 시작 클래스 실행 애플리케이션:

package com.bjpowernode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
로그인 후 복사

hello.html에 추가 가능: 인기 있는 태그에서 해결되지 않음,

xmlns:th를 작성할 때 프롬프트 메시지가 없습니다. ="http://www.thymeleaf.org" 태그에 th를 다시 작성하면 프롬프트 기록이 표시됩니다

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>hello html</title>
</head>
<body>
   <h4>使用Thymeleaf的例子</h4>
   <!--使用模板th:text="${data}"获取后端request的作用域中的数据,把data数据替换文本,text表示取数据-->
   <p th:text="${data}">想显示数据</p>
   <p th:text="${data}">显示</p>
</body>
</html>
로그인 후 복사

사용 모델:

SpringBoot Thymeleaf 템플릿 엔진 예제 분석컨트롤러 내:

package com.bjpowernode.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
public class HelloThymeleafController {
    @RequestMapping("/hello")
    public String helloThymeleaf(Model model, HttpServletRequest request){
        //添加数据到request作用域,模板引擎可以从request中获取数据
        request.setAttribute("data","欢迎使用Thymeleaf模板引擎");
        //使用model和request作用域是一样的 实际上model中的数据就是放到request作用域中的
        model.addAttribute("mydata","model中的数据");
        //指定视图 模板引擎使用的页面(html)
        //逻辑名称
        return "hello";
    }
}
로그인 후 복사

hello.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>hello html</title>
</head>
<body>
   <h4>使用Thymeleaf的例子</h4>
   <!--使用模板th:text="${data}"获取后端request的作用域中的数据,把data数据替换文本,text表示取数据-->
   <p th:text="${data}">想显示数据</p>
   <p th:text="${mydata}">显示</p>
</body>
</html>
로그인 후 복사

speingboot 구성 파일 application.properties: 템플릿 엔진에서 일반적으로 사용되는 관련 설정, 기본적으로 기본값은 없습니다:

SpringBoot Thymeleaf 템플릿 엔진 예제 분석

# 개발 단계에서는 템플릿 전송 캐시를 끄고, 변경 사항이 즉시 적용되도록 설정됩니다. true이면 템플릿 캐시가 사용됩니다. 두 번째로 액세스하면 메모리의 데이터가 사용되며 템플릿은 더 이상 구문 분석되지 않습니다.

spring.thymeleaf.cache=false

#Encoding format
spring.thymeleaf. UTF-8

#템플릿 유형(기본값은 html, 템플릿은 html 파일이므로 웹 페이지를 템플릿으로 지원할 뿐만 아니라 다른 카테고리도 지원합니다)
spring.thymeleaf.model=HTML
#접두사 템플릿: 기본값은 클래스 경로입니다. classpath:/templates Directory
spring.thymeleaf.prefix=classpath:/templates/
#Suffix
spring.thymeleaf.suffix=.html

위 내용은 SpringBoot Thymeleaf 템플릿 엔진 예제 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:yisu.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!