Spring Boot 2 quick tutorial: WebFlux integrated Thymeleaf (V)

No external: as readers continue to put together several new tutorials covering Spring Boot, Spring Cloud, micro-service architecture and other PDF.
Access: public attention to the right number, "Masons BYSocket", to receive it!


Abstract: Original Source https://www.bysocket.com "Public number: masons BYSocket 'attention and welcome to reprint, reserved summary, thank you!

This is the first 105 original mason

Article project:
* the JDK 1.8
* Maven 3.5.2
* the Spring the Boot 2.1.3.RELEASE
* Project name: springboot-webflux-4-Thymeleaf
* Project address: see end of text

Foreword

Last lecture, we use MongoDB to achieve WebFlux operations on the data source. So we have the data needed to render to the front to show users. This is the View layer article concerned. There are many forms View, such as JSON and HTML. Development of common template language is very common to have Thymeleaf, Freemarker and so on. that

What is a template language?

Common language template contains the following concepts: data (Data), the template (Template), template engine (Template Engine) and the resulting document (Result Documents).

  • data

And the data is a representation of the information carrier, may be symbols, words, figures, voice, images and video. Data and information are inseparable, the expression data information, the data information is a connotation. Does not make sense data itself, the data only when the impact on the real behavior become information.

  • template

Template, a blueprint that has nothing to do with a type of class. When using a template compiler will instantiate a template argument according to the template, to obtain a type-specific classes.

  • Template engine

Template engine (here especially for Web development template engine) is to make the user interface and business data (content) resulting from the separation, it can generate a document in a specific format, for a website template engine will generate a standard HTML document.

  • The results document

A particular document format, such as the site for the template engine will generate a standard HTML document.

Template Language wide range of uses, common uses are as follows:

  • Page rendering
  • Document Generation
  • Code Generation
  • All "Data + text template =" application scenarios

Spring Boot template language is recommended Thymeleaf, that

What is Thymeleaf?

The official explanation is as follows:

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

Thymeleaf modern template language engine that can run independently to serve the Web. The main goal is to provide a template for the development of natural, and can accurately display inside HTML.

Thymeleaf is a new generation of Java template engine, it is recommended after Spring 4. Spring 5 is now naturally more recommended.

structure

Mentioned above similar engineering structures, preparation of a new project this case. Project Figure:

file

Contents are as follows

  • org.spring.springboot.webflux.controller – Controller 层
  • org.spring.springboot.dao - data manipulation layer DAO
  • org.spring.springboot.domain - Entity class
  • org.spring.springboot.handler - Yewuluojiceng
  • Application - application startup class
  • application.properties - Application Profiles
  • pom.xml maven configuration
  • application.properties profile

Templates will use the following two directories

  • static directory which contains CSS, JS files and other resources
  • templates directory which contains views

This article focuses on writing Controller layer and templates view.

New POM dependence and configuration

The new configuration dependencies in pom.xml:

  <dependencies>

    <!-- Spring Boot Web Flux 依赖 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

    <!-- 模板引擎 Thymeleaf 依赖 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>


    <!-- Spring Boot Test 依赖 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- Junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  </dependencies>

Here we added Thymeleaf dependent, but not in application.properties - Application Profile Configuration people of any configuration. Default startup its default configuration, the reference Thymeleaf To modify the configuration dependent configuration, as follows:

spring.thymeleaf.cache=true # Enable template caching.
spring.thymeleaf.check-template=true # Check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Check that the templates location exists.
spring.thymeleaf.enabled=true # Enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.max-chunk-size= # Maximum size of data buffers used for writing to the response, in bytes.
spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

Including common encoding, whether to open the cache, and so on.

WebFlux used Thymeleaf

In CityWebFluxController control layer, add the following two methods:

    @GetMapping("/hello")
    public Mono<String> hello(final Model model) {
        model.addAttribute("name", "泥瓦匠");
        model.addAttribute("city", "浙江温岭");

        String path = "hello";
        return Mono.create(monoSink -> monoSink.success(path));
    }

    private static final String CITY_LIST_PATH_NAME = "cityList";

    @GetMapping("/page/list")
    public String listPage(final Model model) {
        final Flux<City> cityFluxList = cityHandler.findAllCity();
        model.addAttribute("cityList", cityFluxList);
        return CITY_LIST_PATH_NAME;
    }

Explain the following syntax:

  • Return value String Mono or will do, but Mono represents my return View also callback.
  • return string corresponding template directory name in the resources / templates of.
  • Model data objects to bind to the view
  • Usually with a centralized view of the path of constant Administrative Templates

Tymeleaf view

And then write two views hello cityList, codes are as follows:

hello.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <title>欢迎页面</title>
</head>

<body>

<h1 >你好,欢迎来自<p th:text="${city}"></p>的<p th:text="${name}"></p></h1>

</body>
</html>

cityList.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <title>城市列表</title>
</head>

<body>

<div>


    <table>
        <legend>
            <strong>城市列表</strong>
        </legend>
        <thead>
        <tr>
            <th>城市编号</th>
            <th>省份编号</th>
            <th>名称</th>
            <th>描述</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="city : ${cityList}">
            <td th:text="${city.id}"></td>
            <td th:text="${city.provinceId}"></td>
            <td th:text="${city.cityName}"></td>
            <td th:text="${city.description}"></td>
        </tr>
        </tbody>
    </table>

</div>

</body>
</html>

Common syntactic sugar as follows

  • $ {...} variable expression
  • th: text processing Tymeleaf expression
  • th: each traversal expression, may traverse objects: to achieve java.util.Iterable, java.util.Map (java.util.Map.Entry taken when traversing), and the like Array

There are many use refer to the official party document http://www.thymeleaf.org/documentation.html

Run the project

The operation of the project under verification. IDEA using the right side of the toolbar, click the Maven Project Tab, click the Maven plugin using the following  install command. Or use the command line of the form, in the project root directory, execute instructions Maven clean-up and installation of:

cd springboot-webflux-4-thymeleaf
mvn clean install

See the success of the output in the console:

... 省略
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:30 min
[INFO] Finished at: 2017-10-15T10:00:54+08:00
[INFO] Final Memory: 31M/174M
[INFO] ------------------------------------------------------------------------

IDEA performed in the  Application class started, the normal mode or any Debug mode. You can see the output of a successful run in the console:

... 省略
2018-04-10 08:43:39.932  INFO 2052 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext     : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2018-04-10 08:43:39.935  INFO 2052 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080
2018-04-10 08:43:39.960  INFO 2052 --- [           main] org.spring.springboot.Application        : Started Application in 6.547 seconds (JVM running for 9.851)

Open the browser and go to http: // localhost: 8080 / city / hello, you can see the response as shown:

file

Continue to visit http: // localhost: 8080 / city / page / list, we found no value, according to the last lecture insert a few data can have a value, as shown:

file

to sum up

Here, we discuss how to integrate Spring WebFlux Thymeleaf. Other integrated template language Thymeleaf, Freemarker, on any different. Below, we will be able to integrate Thymeleaf and MongoBD, to achieve an overall simple cases.

The sample code

Readers can view the examples in this article by the following warehouse module project name: 2-x-spring-boot-webflux-handling-errors:

If you are interested in these, welcomed the star, follow, bookmarking, forwarding support!

Reference material

  • Spring Boot 2.x WebFlux Series: https: //www.bysocket.com/archives/2290
  • spring.io official documents

The following tutorial Maybe you will be interested in the topic


(Focus on micro-channel public number, receive a selection of dry goods Java learning materials) 
(add my micro letter:. Bysocket01 added purely technical exchange group, growing technology)

Guess you like

Origin www.cnblogs.com/Alandre/p/10954254.html