SpringBoot integration Thymeleaf- based version SpringBoot2.X

1, why use Thymeleaf template engine? Now we do not have a separate front and rear end it?

Bear dei them, do not worry, let's talk about why start with Thymeleaf template engine, we take care of these lovely little white shoes under the care of ....

Why start with Thymeleaf template engine? jsp she not sweet thing? First of all front-end to our page, html page is, if it is before we develop, we need to turn them into a jsp page, jsp advantage is that when we find out some of the data forwarded to the JSP pages later, we can easily use jsp data display, and interactions. jsp supports very powerful features, including a write Java code ....... Yes, give praise jsp meal.

But then, SpringBoot jar project is the way, not the way of war, and SpringBoot with or embedded Tomcat, so, what he is now the default is not supported by the jsp ....... yes then a backhand to jsp mouth son.

It does not support jsp, if the way we use pure static pages, it gives us direct development will bring great trouble, how to do it, SpringBoot recommend using a template engine. There are many template engines, such as Thymeleaf, , Velocity, FreeMarkerbut the idea is the same, this need not worry, springboot recommended Thymeleaf, of course, programmers are basically Thymeleaf template engine, template engine Thymeleaf in the industry is the industry's praise.

Now we do not have a separate front and rear end it? Vue she not sweet thing? Although now slowly before and after the popular end of the separation development, but there are some “灵玩不灵”development companies still around doing, regardless of the end, and the back-end development, regardless of the front, we'll need to back-end page template engine [in fact, even before and after the end of the separation will need to use page templates in some scenarios, for a typical chestnut: 邮件发送模板].

2, SpringBoot1.X 2.X version with fuse

With the development of science and technology, social progress, companies in the running, programmers roar. Wake up, young man, now in 2020, before inevitably hear or see the online article said the first step of what you want to import Thymeleaf template dependencies, spade default in previous versions is Thymeleaf is 2.1.6x , to develop based on 3.x, and then have to write down the tag in pom.xml properties in the following two codes

<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>		
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
复制代码

Said layout features support program needs thymeleaf3 main program, layout2 above, that the 3.x manually override the dependence of thymeleaf in 2.x.

He said a lot, I just want to say: the current version of the basic default is thymeleaf3.x, now in 2020, and even young students are learning basic SpringBoot2.X version. If you are still using SpringBoot1.X, that not to us, you're a good man.

If you're still unsure, you can do the following big check to check thymeleaf version:

Here Insert Picture Description

3, SpringBoot2.X version integration Thymeleaf

I have to say (pull) a lot better to be whole:

Here Insert Picture Description
Would like above, it may be a different idea versions will choose a different version of SpringBoot situation, this is normal, life advice: No matter consequently do not pursue the latest version, you are having seems to be very high-end leather, while a line of cigarette a day of change bug look also very chic ~ ~ embarrassed, and I am not here outlines.

After checking Thymeleaf, Once created, pom.xml rely on default as follows:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
复制代码

That is, the dependence and introduced Thymeleaf, you do not need a guide. Here basically it can be said that integration is completed, the next talk about the power of Thymeleaf.

4, Thymeleaf rendering

Thymeleaf rendering rules, you can automatically find its configuration file to see its usage rules, as follows:

Here Insert Picture Description
Key Code:

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
        private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
        public static final String DEFAULT_PREFIX = "classpath:/templates/";
        public static final String DEFAULT_SUFFIX = ".html";
        private boolean checkTemplate = true;
        private boolean checkTemplateLocation = true;
        private String prefix = DEFAULT_PREFIX;
        private String suffix = DEFAULT_SUFFIX;
        private String mode = "HTML";
        private Charset encoding = DEFAULT_ENCODING;
        private boolean cache = true;
        //...
复制代码

Source code analysis, as follows:

1, first through @ConfigurationProperties annotation, the application.properties prefixed spring.thymeleaf property binding configuration and in this class.

 

2, the first three static variables, and a default encoding format, ViewResolver prefix, suffix and the like.

 

3, the first three lines according to the configuration, it can be seen, Thymeleaf the default location of the template in resources / templates directory>, default suffix is HTML .

 

Note: These configuration, if the developers do not provide their own, then use the default, if they provided, then application.properties to the spring.thymeleaf start the relevant configuration.

Yes, they simply default rules are as follows:

Default prefix :DEFAULT_PREFIX = "classpath:/templates/"

 

Default suffix :DEFAULT_SUFFIX = ".html"

Exactly like Spring MVC mapping, of course, if you want to modify these configurations can be modified to cover only the global configuration file, we generally do not cover, unless special needs.

Also to be mentioned is that automated configuration class Spring Boot to Thymeleaf provided org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration , wherein some of the key source as follows:

@Configuration
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {
   //....
}
复制代码

analysis:

You can see from the source code, this automated configuration class, first @EnableConfigurationPropertiesimport ThymeleafProperties, then @ConditionalOnClasswhen the notes indicate the presence of TemplateMode and SpringTemplateEngine like the current system, the current class of automated configuration to take effect, that is, as long as the project introduced Thymeleaf related to dependence, this configuration will take effect.

The default configuration we almost do not need to make any changes can be directly used. If you have special needs, it can application.propertiesbe configured to the spring.thymeleafproperty can begin with their own tailor-made, of course, I can not have this demand, unless someone hit me, otherwise I would want to order this demand habit. If you have to change the proposed reference SpringBoot official documents

5, the test is successful integration Thymeleaf

Yes, who will step above, only after the integration test is considered Thymeleaf successful completion of the integration, which is wrong at this stage a variety of reasons came out.

Controller Code

First written Controller code we write is not so complicated, how simple demo how to

@Controller
public class HelloController {
    @GetMapping("/su")  
    public String success(){
        return "success";    //  相当于访问 classpath:/templates/success.html
    }
}
复制代码

html page code

Write page code, do you want to pay attention to this page code classpath:/templates/directory

Here Insert Picture Description
code show as below:

<!DOCTYPE html>
<html lang="en">  
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>整合Thymeleaf已经success哈哈哈哈</h1>

</body>
</html>
复制代码

Access tests

accesshttp://localhost:8080/su

Here Insert Picture Description
As it indicates the effect of successful integration.

6, SpringBoot integration issues that may arise Thymeleaf

Here Insert Picture Description

This abnormality is common will have to see specific information on abnormalities, such as routing page it says is the emergence of the ring, equivalent to a circular reference, may be their own access path and name of the HTML file the same name, may wish to try a change request path .

As another example, see the following general printing information specific

Here Insert Picture Description
Here summarize and resolve the reason for the exception:

. 1, the class does not start position of Application: Application To class on the outermost side, i.e., comprising all the sub-packets, spring-boot automatically loads all the starting components in the class where the package and its sub-packets. If the class does not start on the outermost will error, the correct position is as follows:

Here Insert Picture Description
2, springboot configuration file is incorrect: on application.yml or application.properties configuration problems in view file parser. In the pom case file spring-boot-starter-paren

When using a higher version configuration: spring.mvc.view.prefix / spring.mvc.view.suffix version lower when using the configuration: spring.view.prefix / spring.view.suffix

3, url and annotation @XXXMapping access path controller ( "/ xxxx") does not match, as shown below:

Here Insert Picture Description
4, this last reason in particular pit Oh, you will find that you are in line with the above, but still still being given, which is amazing, in fact, for this reason I was in the tank for a morning ---- version is too high . You might say idea is selected by default when 2.1.X up, the basic version is not what you want, in fact, this is not a big problem, in fact, can be modified in pom.xml, as follows:
Here Insert Picture Description
If this process there is an exception occurs, so that you fear the Senate Health, remember that the best way to overcome fear is to face the fear, wake up young, I giao a mile giaogiao wailing .. .. Ow ow ow ow .. ow ow ow ............................ Orly to! ! !

If this article there is a little bit of help to you, then please point a chant praise, thank you ~

Finally, if there is insufficient or is not correct, please correct me criticism, grateful! If you have questions please leave a message, the absolute first time to reply!

I welcome you to focus on the public number, there are some java learning materials and a large wave of java e-books, such as Zhou Zhiming teacher depth java virtual machine, java programming ideas, the core technology volume, Westward design patterns, java concurrent programming combat ... .. is a java Bible, do not say fast car on Tomcat, ye who go! The main thing is to explore technology, yearning technology, the pursuit of technology, said good pots Friends is coming Oh ...

Here Insert Picture Description
reference:

SpringBoot official document: docs.spring.io/spring-boot...

www.imooc.com/article/293…

blog.csdn.net/qushaming/a…

Guess you like

Origin juejin.im/post/5e0bf8616fb9a048346280ea