Interested friends can go to know about the other several articles have been published, your praise is the biggest support for me, thank you!

  • The article directories

SpringBoot takeoff road -HelloWorld

(two) SpringBoot takeoff road – analysis of the principle of entry

(three) SpringBoot takeoff road -YAML configuration summary (entry must know will)

(4) SpringBoot takeoff road – static resource processing

(five) SpringBoot takeoff road -Thymeleaf template engine

(6) SpringBoot takeoff road – integration jdbctemplate-druid-mybatis

(7) SpringBoot launch road – integration of SpringSecurity (Mybatis, JDBC, memory)

(eight) SpringBoot take-off path – integration Shiro detailed tutorial (MyBatis, Thymeleaf)

SpringBoot -Swagger 2 And 3

Description:

  • SpringBoot takeoff road series of articles involved in the source code, are synchronized to github, there is a need for small partners, go down at will
    • Github.com/ideal-20/Sp…
  • Untalented and uneducated, will point to shallow knowledge, we should be a tool to see it, do not like to spray ha ~

(a) template engine introduction

(1) Development mode

In normal development, when it comes to a complete front and back end project, there are two approaches:

  • One is the separation of the front and back ends, that is to say, the agreed interface, through asynchronous way, with Json string as the content of the transfer, the background for some business logic, the front is responsible for the interface, as well as through JS data processing and page beautification.

  • There is another way is the template engine way, this way is not too novel, you can simply understand as JSP which mode

Separation start more popular now, both before and after the end, but a lot of the old project, or write things alone, I feel using template engine is also very good choice, there are some time to find the background of open source template, some have used the Thymeleaf, let alone for learning attitude, what kind of techniques can be learned

For the second way to continue to say, JSP we should be familiar with, such as the front end of an HTML page, we will go to rewrite this page for JSP page, we can use JSP is easier to achieve the display of data, so why not continue to use JSP and to use other template engine?

Note: Thymeleaf and Freemarker have their own characteristics and may feel uncomfortable with another way of using them. There is no need to argue about which is better, just like it

(2) Why template engine

In the case of Springboot, JSP is not officially recommended

Springboot 2.2.7

Address: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/html/spring-boot-features.html#boot-features-jsp-limitat ions

Springboot: 7.1.10. Template Engines

As well as REST web services, you can also use Spring MVC to serve dynamic HTML content. Spring MVC supports a variety of templating technologies, including Thymeleaf, FreeMarker, and JSPs. Also, many other templating engines include their own Spring MVC integrations.

Spring Boot includes auto-configuration support for the following templating engines:

FreeMarker, Groovy, Thymeleaf, Mustache

If possible, JSPs should be avoided. There are several known limitations when using them with embedded servlet containers.

In general, the above paragraph tells us that if you want to display HTML content dynamically, you can use template techniques like FreeMarker, Groovy, Thymeleaf, Mustache

Finally, Springboot suggests that we avoid JSPS as much as possible, and provides some advice

Springboot:7.4.5. JSP Limitations

When running a Spring Boot application that uses an embedded servlet container (and is packaged as an executable archive), there are some limitations in the JSP support.

  • With Jetty and Tomcat, it should work if you use war packaging. An executable war will work when launched with java -jar, and will also be deployable to any standard container. JSPs are not supported when using an executable jar.

  • Undertow does not support JSPs.

  • Creating a custom error.jsp page does not override the default view for error handling. Custom error pages should be used instead.

The second point is that Undertow supports JSPS, and the third point is about error coverage

The first two are not what I want to say. Let’s focus on the first point: if you put a war package using JSP into Tomcat or another container, it will work. Of course, you can use java-jar to run it, but if you execute the jar package directly, it will not work

In other words, the type of packaging determines whether the JSP can be parsed and used properly. Also, Tomcat is embedded in SpringBoot, and SpringBoot programs often run independently of the container. If JSP is used, additional addresses are required to store generated servlets. There may be security issues, as JSPS are not supported by default

(3) Does SpringBoot recommend Thymeleaf?

There are articles all over the web, SpringBoot officially recommends Thymeleaf. I looked at the documentation for SpringBoot 2.2.7 (it seems that 2.3.0 is also a GA, this part is not changed) and I couldn’t find an exact statement about the recommendation myself

Springboot: 7.1.10. Template Engines

  • In Springboot — SpringBoot Features — 7.1.10. Template Engines, Springboot provides support for auto-assembly of Thymeleaf, But there’s also support for FreeMarker, Groovy, and Mustache autoassembly, and I don’t see a recommendation here

For SpringMVC: 1.10.1 Thymeleaf

Thymeleaf is a modern server-side Java template engine that emphasizes natural HTML templates that can be previewed in a browser by double-clicking, which is very helpful for independent work on UI templates (for example, by a designer) without the need for a running server. If you want to replace JSPs, Thymeleaf offers one of the most extensive set of features to make such a transition easier. Thymeleaf is actively developed and maintained. For a more complete introduction, see the Thymeleaf project home page.

For SpringMVC: 1.10.2 FreeMarker

Apache FreeMarker is a template engine for generating any kind of text output from HTML to email and others. The Spring Framework has built-in integration for using Spring MVC with FreeMarker templates.

  • Take a look at the SpringMVC 5.2.6.RELEASE documentation. There is no mention of support or recommendations for templates, but a few common ones such as Thymeleaf, FreeMarker, etc

So, in my opinion, SpringBoot only provides several alternatives to JSP, and does not specify any recommendations. Of course, if I did not notice, you can also leave a comment and share with me

(4) Summary of this part

With all that said, it’s a no-brainer that SpringBoot doesn’t recommend JSP, but it doesn’t specify which engine template to recommend, and you can pick your own (FreeMarker, Groovy, Thymeleaf, Mustache)

(two) JSP really a little trouble

If you really want to use JSP in SpringBoot, you can do so with some additional configuration

(1) Import dependencies

When initializing, I chose the basic Web and devTools for hot deployment, so just checking Web is ok

Spring-boot-starter-tomcat spring-boot-starter-tomcat spring-boot-starter-tomcat spring-boot-starter-tomcat spring-boot-starter-tomcat spring-boot-starter-tomcat spring-boot-starter-tomcat spring-boot-starter-tomcat The former includes servlet-API and built-in servlet containers, while the latter is an EL expression package, so all we need to do is introduce JSTL and tomcat-Embed – Jasper for compiling JSPS

<dependencies>
	<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
     </dependency>

    <! -- jsp begin-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
    <! -- jsp end-->
</dependencies>
Copy the code

(2) Write background code

Entity class

Start by creating a User entity and simply write three members

public class User {
    private String username;
    private Integer age;
    privateString address; . Get set toString method}Copy the code

Control layer

This code is shallow enough, just go back to the List and iterate through it

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/list")
    public String list(Model model) {
        System.out.println("Query all");

        User u1 = new User();
        u1.setUsername("Steven");
        u1.setAge(20);
        u1.setAddress("Beijing");

        User u2 = new User();
        u2.setUsername("Jack");
        u2.setAge(30);
        u2.setAddress("Shanghai");

        List<User> users = new ArrayList<User>();

        users.add(u1);
        users.add(u2);

        model.addAttribute("users", users);
        return "list"; }}Copy the code

(3) write the JSP

In the main folder, create a webApp folder and a Web-INF folder to store the JSP files (I also created a Pages folder under this folder for personal habits). Static folders are still placed under resources static resources folder such as Static Public etc

Location: SRC/main/webapp/WEB – INF/pages/list. The JSP

So here’s a Demo of walking through a table

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"% > <! DOCTYPE html> <html> <head> <meta charset="UTF-8">
    <title>list all</title>
</head>
<body>
    <table border="1">
        <c:forEach items="${users}" var="user">
            <tr>
                <td>${user.username}</td>
                <td>${user.age}</td>
                <td>${user.address}</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>
Copy the code

(4) Modify the configuration

These pages will not be found without configuration, so you need to configure the JSP mapping path and suffix

spring.mvc.view.prefix=/WEB-INF/pages/
spring.mvc.view.suffix=.jsp
Copy the code

(5) test

Run startup class access directly

Accessible to

Type jar to run access

Maven Projects –> Lifecycle –> clean –> package

Our JSP page is lost

(6) Multi-module project 404 problem

The main reason is that the correct path can not be found, so you need to set the Working directory to the module Working folder $MODULE_WORKING_DIR$,

How to set: Open Run/Dedug Configurations, and then modify

About JSP I did not use in SpringBoot, also did not have a detailed study, before I saw an article has summarized the pit about JSP, we are interested in maybe can understand

https://juejin.cn/post/6844903591245774856

(three) Try Thymeleaf

(1) Simple evaluation

A: advantages

First, the configuration is simple. SpringBoot supports auto-assembly for several template engines, including Thymeleaf, so simply importing dependencies can be used quickly

Second, Thymeleaf is “elegant” because the binding or control is done as attributes, so the original structure of HTML is not broken, which has an advantage that other template engines don’t have: It can be rendered normally by the browser, that is, it can be accessed directly (for example, JSP cannot be accessed directly outside the container)

B: shortcomings

Label checking is very strict and sometimes crazy….

There are a variety of expressions and tags. {} Different symbols before curly braces stand for different meanings, for example, ${… } variable expressions, *{… } Select expression

If you’re used to freemarker writing, Thymeleaf can be a bit of a hassle because of the different angles or ways of writing

C: About performance

In terms of performance, Thymeleaf has improved a lot since 3.x, but I checked the data and it seems that it is still not that ideal, but personally, I have a backend to write the page, a mess of JS, CSS and various increased overhead, some effects of Thymeleaf, It doesn’t seem to have much to do with me and You.

Introducing the Thymeleaf # # (2)

You have to introduce dependencies before you can use them, right? You can go to Thymeleaf, or you can go to Springboot, but I prefer the latter

Thymeleaf website: https://www.thymeleaf.org

Springboot website:

The official website is in the 2.3.0 version, you are still not out of the Pom, but you can go to see 2.2.7

Version Name Description Pom
2.3.0 spring-boot-starter-thymeleaf Starter for building MVC web applications using Thymeleaf views Temporarily does not provide
2.2.7 spring-boot-starter-thymeleaf Starter for building MVC web applications using Thymeleaf views Pom

2.2.7 Pom

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
	<groupId>org.thymeleaf</groupId>
	<artifactId>thymeleaf-spring5</artifactId>
</dependency>

<dependency>
	<groupId>org.thymeleaf.extras</groupId>
	<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
Copy the code

That’s one way to do it, but Springboot has packaged all of this stuff for us right out of the box

So the final introduction is:

A: Pom increases dependency

<! --thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Copy the code

B: Select related components during initialization

(3) Template page storage location

Once you’ve introduced dependencies, you need to figure out where to put your pages. You can create webApp WEB-INF and configure the JSPS shown earlier, and you can just put your pages in the auto-generated templates folder, right

The path is SRC — main — resources — template

To see why: Take a look at the ThymeleafProperties configuration class, which has its prefix and suffix specified

@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";

   // Check whether the template exists before rendering it
   private boolean checkTemplate = true;
    
   // Check whether the template location exists
   private boolean checkTemplateLocation = true;

   // Prefixes the URL with the view name
   private String prefix = DEFAULT_PREFIX;

   // The suffix appended to the view name when building the URL
   private String suffix = DEFAULT_SUFFIX;

   // The template pattern to be applied to the template
   private String mode = "HTML";

   // Template file encoding
   private Charset encoding = DEFAULT_ENCODING;
Copy the code

(4) Entry program experience

1. Write controllers

@Controller
public class TestController {
    @RequestMapping("test")
    public String test(Model model){
        String hello = "Hello Thymeleaf";
        model.addAttribute("hello",hello);
        return "test.html"; }}Copy the code

2. Write pages

The page looks like a normal HTML page, with a few differences: a namespace constraint is introduced at the top, using syntax like th: XXX, for example, th:text, and then ${hello} introduces hello from the control layer

${hello} should be red, but it can be run, as shown below

<! DOCTYPEhtml>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Test</title>
</head>
<body>
  <h2>Test success</h2>
  <! --/*@thymesVar id="hello" type="java.lang.String"*/-->
  <p th:text="' Received data: '+ ${hello}"></p>
</body>
</html>
Copy the code

3. Test results

(5) Label red

<p th:text="' Received data: '+ ${hello}"></p>
Copy the code

For example, ${hello} would be red if left untouched, with a wavy red line underneath it

Reason: Although the back-end model added data, but because there is no program running, front-end files do not know, so this time there will be red wavy line, in fact, normal operation is no problem, but it looks very annoying

There are three solutions:

  • Autocomplete shortcut keys, automatically write the above comments, and then write their own type
<! --/*@thymesVar id="hello" type="java.lang.String"*/-->
Copy the code
  • In IDEA, a global override is performed

(6) Characteristics and description of Thymeleaf

After a simple routine, obviously, we also have a certain feeling, and before the introduction of the program, we have said some of its advantages and disadvantages ah, but to tell the truth, there is no special feeling, we just follow this example, to give you a simple say about its characteristics and some points of attention

1. First of all, we talked about Thymeleaf being “elegant” because bindings or controls are done as properties, as in the following paragraph

 <p th:text="' Received data: '+ ${hello}"></p>
Copy the code

If you were to write ${hello} in HTML it would be a bit messy, but with Thymeleaf, the expression is written in a custom property, so the content of the expression is treated as a normal string in a static environment and the browser will not report an error

2. At the same time, we can see that the original structure of HTML has not been destroyed, and it still looks like HTML at a glance

3. According to the above characteristics, Thymeleaf can also be directly run by the browser in the static environment. In the static environment, the contents of th instruction will not be recognized, but no error will be reported

(4) Basic grammar

(1) Introduce namespace constraints

As you can see, the following is written in th:*, and for this to work, the constraint must be introduced before the

<html xmlns:th="http://www.thymeleaf.org">
Copy the code

We’ve already used it in the above routine, but let’s start with some more formal syntax

(2) Variable syntax and th:text

A: Give an example

A simple variable to look at above, the introductory routine, actually very simple, let’s look at the value of the variable in the object

1. Write entities

Start by creating two entities, the student class and the course class, and in the student class, reference the course class

public class Student {
    private String name;
    private Integer age;
    privateCourse course; . Omit get set toString}Copy the code
public class Course {
    private String name;
    privateString teacher; . Omit get set toString}Copy the code

2. Write Conteoller

@Controller
public class TestController {
    @RequestMapping("testStudent")
    public String testStudent(Model model){
        // Assign values to both objects
        Student stu = new Student();
        Course course = new Course();

        course.setName("JavaEE course");
        course.setTeacher("Miss Jack");

        stu.setName("Zhang");
        stu.setAge(25);
        stu.setCourse(course);

        model.addAttribute("student",stu);
        return "test.html"; }}Copy the code

3. Write pages

  • ${} is used to fetch variables in the model. For example: Student. Name is ogNL. The property name

  • The expression is written in a tag property called th:text, called a directive

  • The th:text is called text substitution. The function is to evaluate an expression or variable, and then display the result in the body of the contained HTML tag, replacing the original text

  • So you can put some default values in the tag, so that you can compare it statically, and when you run it, that text is replaced with background data

<p>Student Name:<span th:text="${student.name}"></span> </p>
<p>Student Age:<span th:text="${student.age}"></span> </p>
<p>Course name:<span th:text="${student.course.name}"></span> </p>
<p>Lecturers:<span th:text="${student.course.teacher}"></span> </p>
Copy the code

4. Implementation effect

B: Add th: UText

Th :utext, th:text, th:utext

  • Th :text Displays in plain text without parsing HTML tags or elements in the content

  • Th: UText parses and displays the entire content as HTML, which means that the test , for example, will be displayed as a secondary header

C: Reduce the number of variables written

When there is too much data involved and we need to write student for each one, we can also write it as a custom variable

  • Th :object=”${student}

  • You only need to get these attributes from student by *{attribute name} when referencing them

<h5 th:object="${student}">
  <p>Student Name:<span th:text="*{name}"></span> </p>
  <p>Student Age:<span th:text="*{age}"></span> </p>
  <p>Course name:<span th:text="*{course.name}"></span> </p>
  <p>Lecturers:<span th:text="*{course.teacher}"></span> </p>
</h5>
Copy the code

(3) String splicing expression

That said, there are a lot of other things that we don’t want to be parsed as variables, called literals. Common types include: A string, or a number, for example, can be written in single quotes, whereas a number can be used without any manipulation, and can be used with arithmetic. Right

And of course, a lot of times, the data that we’re fetching, we’re going to have to display it with some strings on the page, so one way to do that is to just write something out there like

<p>Student Name:<span th:text="${student.name}"></span> </p>
Copy the code

Another common way is to concatenate a string with an expression.

  • (1) Put the p tag inside th:text, using single quotes
<p> <span th:text=${student.name}"></span> </p>
Copy the code
  • (2) If a large number of concatenations are involved, using single quotation marks will be confusing to write and read, so it can be simplified:
<p> <span th:text="| name: ${student. The name} |"></span> </p>
Copy the code

By the way, when running in a static environment, there is no string to display, only when running with SpringBoot

(4) operator

In terms of operators, I wrote them according to section 4 of Standard Expression Syntax in the official document of Thymeleaf. Some of them are still commonly used. Not all the examples are tested and some representative ones are given

A: Arithmetic operations

1. Supported operators

  • Binary operations: +, -, *, /, %
  • Unary operation: – (negative)

2. Test code

Note: operators are best left outside because they are inside {} and expressions are evaluated using the OGNL engine; If the operator is external, the expression is evaluated using the Thymeleaf engine

<p>Student age =<span th:text="${student.age} "></span> </p>
<p>Student age / 2 =<span th:text="${student.age} / 2 "></span> </p>
<p>Student age % 2 =<span th:text="${student.age} % 2 "></span> </p>
Copy the code

3. Implementation effect

B: Boolean operation

1. Supported operators

  • Unary operators: and, or
  • Binary operators:! , not

C: Comparison operation

1. Supported operators

  • >, <, >=, <= (gt, lt, ge, le)
  • ==,! = ( eq , ne )

2. Description:

  • > and < are treated as tags, so they cannot be used directly. You can use aliases in parentheses instead

  • = = and! = has a similar function to equals in addition to comparing values

Test your code

<p>Student Name:<span th:text="${student.name}"></span> </p>
<p>The student's name is Zhang SAN =<span th:text=${student.name} == ${student.name}"></span> </p>

<p>Student age is 25 =<span th:text="${student.age} == 25 "></span> </p>
<p>Student age % 2 is 0 =<span th:text="${student.age} % 2 == 0 "></span> </p>
Copy the code

4. Implementation effect

D: Conditional operation

  • If-then: (if) ? (then)
  • If-then-else: (if) ? (then) : (else)
  • Default: (value) ? : (defaultvalue)

2. Test code

<p>Student name =<span th:text=${student.name} == ${student.name};></span> </p>
Copy the code

3. Implementation effect

(5) Conditional operation is supplemented

Conditional operations are put into the operator, showing the ternary operation, because logical judgments are very common, so we add

A: if

Nothing to say, just a simple judgment, okay

1. Test code

<p>Whether the student is of age:<span th:if="${student.age} >= 18 ">adult</span> </p>
Copy the code

Only when the age is > 18 will the words “adult” be displayed

B: unless

Unless is the opposite of if: if is executed if conditions are met, and unless is executed if conditions are not met

1. Test code

<p>Whether the student is of age:<span th:unless="${student.age} >= 18 ">adult</span> </p>
Copy the code

Test it out for yourself

C: the switch

Th :case=”*

1. Test code

<div th:switch="${student.name}">
  <p th:case="Zhang">Name: Zhang SAN</p>
  <p th:case="Bill">Name: Li Si</p>
  <p th:case="Fifty">Name: Wang Wu</p>
  <p th:case="*">Name: Not found</p>
</div>
Copy the code

2. Execution effect

Change the controller and assign the student name to Li Si. Look at the display of the page

(6) Loop grammar

Loops are also very common and are implemented with the th:each directive. Let’s follow a small Demo to see how this works

A: Demo

Create a user class

public class User {
    private String nickname;
    privateInteger age; . Get set toString method}Copy the code

2. Controller adding method

It returns a List of users

@RequestMapping("testUser")
public String testUser(Model model){
    User user1 = new User();
    user1.setNickname("The Flying Penguin");
    user1.setAge(30);

    User user2 = new User();
    user2.setNickname("Sad little Boy");
    user2.setAge(25);

    List<User> list = new ArrayList<User>();
    list.add(user1);
    list.add(user2);

    model.addAttribute("userList",list);
    return "test.html";
}
Copy the code

3. Page code

Note here: userLisr in ${userList} is the set we returned, and user is every user we iterated through, similar to enhanced for in Java

<table border="1">
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr th:each="user : ${userList}">
    <td th:text="${user.nickname}">NULL</td>
    <td th:text="${user.age}">0</td>
  </tr>
</table>
Copy the code

4. Implementation effect

B: Footnote

① Iteration type

There are actually a number of acceptable types of values to be iterated over, such as our ${userList} above

  • Enumeration, the Enumeration
  • Map collections
  • List, array, and any other object that matches the result of an array

The Demo above is more like enhanced for in Java. Enhanced for is easy to traverse, but it has some disadvantages compared to ordinary for. That is, it does not have some state variables, such as start and end, etc., so Thymeleaf provides us with stat objects. Help us make up for that

② Attributes of the stat object

  • Index, the index of the current iteration object, starting from 0
  • Count, the number of elements, starting at 1
  • Size, the total number of elements
  • Current: indicates the current traversal element
  • Even /odd, Boolean, whether the current loop is even/odd, Boolean value
  • First /last, returns first or last, Boolean

1. Test code

<table border="1">
  <tr>
    <th>nickname</th>
    <th>age</th>
    <th>index</th>
    <th>count</th>
    <th>size</th>
    <th>current.nickname</th>
    <th>even</th>
    <th>odd</th>
    <th>first</th>
    <th>last</th>
  </tr>
  <tr th:each="user,userStat : ${userList}">
    <td th:text="${user.nickname}">nickname</td>
    <td th:text="${user.age}">age</td>
    <th th:text="${userStat.index}">index</th>
    <th th:text="${userStat.count}">count</th>
    <th th:text="${userStat.size}">size</th>
    <th th:text="${userStat.current.nickname}">current.nickname</th>
    <th th:text="${userStat.even}">even</th>
    <th th:text="${userStat.odd}">odd</th>
    <th th:text="${userStat.first}">first</th>
    <th th:text="${userStat.last}">last</th>
  </tr>
</table>
Copy the code

2. Execution effect

(5) Built-in methods

(1) Environment and context

Thymeleaf also provides some built-in methods that you can call, but I don’t recommend using the following methods too much. In the front page, try to minimize logic. Here is a screenshot from the official documentation

object role
#ctx Get Thymeleaf’s own Context object
#requset Is the case of a Web application used to get an HttpServletRequest object
#response Is the case of a Web program used to get an HttpServletReponse object
#session Is the case of a Web program used to get an HttpSession object
#servletContext In the case of a Web application, to get an HttpServletContext object

(2) Tool class methods

There are also some built-in objects of tool nature, easy to use, or take a look at the official screenshots, of course, I did not take all of them, if necessary, you can have a look

object role
#dates The object used to handle time (java.util.date)
#calendars Objects that handle dates in the calendar (java.util.calendar)
#numbers Formatted number
#strings Handling strings
#bools Judge Boolean values
#arrays Handle arrays
#lists Working with List collections
#sets Working with sets
#maps Working with the Map collection

(3) Demonstrate

1. Write the Controller method

@RequestMapping("testDate")
public String testDate(Model model){
    model.addAttribute("currentTime".new Date());
    return "test.html";
}
Copy the code

2. Write pages

<p>Present Time:<span th:text="${#dates.format(currentTime,'yyyy-MM-dd hh:mm:ss')}">2020-05-19 00:00:00</span></p>
Copy the code

3. Implementation effect

(6) Commonly used labels

  • Label only do a similar outline directory of use, more detailed usage also need to refer to and practice, but these things still need to pay attention to, often use the wrong

    Supplement:

    • The ${... }: Variable expression
    • * {... }: Select expression
    • # {... }: message (i18n) expression
    • @ {... }: Link (URL) expression
    • ~ {... }: fragment expression

(1) th:text

Text replacement: Mainly used for text display

The first:

<p th:text="' Received data: '+ ${hello}"></p>
Copy the code

The second:

<p>Student Name:<span th:text="${student.name}"></span> </p>
Copy the code

(2) th:utext

Support HTML text replacement, can be used for rich text editor after editing content display to the front page

Th: UText parses and displays the entire content as HTML, which means that the test , for example, will be displayed as a secondary header

<p th:utext="' Received data containing HTML tags: '+ ${test}"></p>
Copy the code

(3) th:if / th:unless

Th :if is used to determine the condition and execute if it is met, while th:unless is the opposite

th:if

<p>Whether the student is of age:<span th:if="${student.age} >= 18 ">adult</span> </p>
Copy the code

th:unless

<p>Whether the student is of age:<span th:unless="${student.age} >= 18 ">adult</span> </p>
Copy the code

(4) th:switch / th:case

Used for multiple judgment of the same grade, that is, multiple selection

<div th:switch="${student.name}">
  <p th:case="Zhang">Name: Zhang SAN</p>
  <p th:case="Bill">Name: Li Si</p>
  <p th:case="Fifty">Name: Wang Wu</p>
  <p th:case="*">Name: Not found</p>
</div>
Copy the code

Note: th:case=”*” indicates the default, put the last will be ok

(5) th:each

It is used to traverse objects in a collection, and is basically the same as < C :forEach> in JSTL

In addition, you can also get some statuses, stat. Check out the loop syntax above

<table border="1">
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr th:each="user : ${userList}">
    <td th:text="${user.nickname}">NULL</td>
    <td th:text="${user.age}">0</td>
      
  </tr>
</table>
Copy the code

(6) th:action

When used for form submission, it is equivalent to the action attribute of the

tag.
<form th:action="@{user/login}" method="post"></form>
Copy the code

(7) th:src

Used to import external resources such as images or JS

<img th:src="@ {... /images/test.jpg}"/>or<script th:src="@ {... /static/register.js}"></script>
Copy the code

(8) th:href

Used to define hyperlinks, equivalent to the href attribute of the tag

Traditional stitching transfer

<a th:href="/showStudent? Id = 123456 & name = zhang SAN"></a>
Copy the code

Pass with one parameter

<a th:href="@{/student/details(studentId=${student.id})}" ></a>
Copy the code

(9) th:value

Used for attribute assignment

<input th:value = "${student.name}" />
Copy the code

##(10) th:object / th:field

Th :object and th:field are used to bind form parameters

1. Write entities

public class LoginUser {
    private String username;
    privateString password; . }Copy the code

2. Write the Controller method

@RequestMapping("/testLogin")
public String testLogin(@ModelAttribute(value = "loginUser")LoginUser loginUser, ModelMap modelMap){

    String username = loginUser.getUsername();
    String password = loginUser.getPassword();

    System.out.println(username);
    System.out.println(password);

    if ("admin".equals(username) && "admin888".equals(password)){
        modelMap.addAttribute("msg"."Successful landing.");
        return "test.html";
    }
    modelMap.addAttribute("msg"."Login failed");
    return "test.html";
}
Copy the code

3. Write pages

<form id="login" th:action="@{/testLogin}" th:object="${loginUser}">
  <input type="text" value="" th:field="*{username}"></input>
  <input type="text" value="" th:field="*{password}"></input>
  <input type="submit" value="Submit" />
  <span th:text="${msg}"></span>
</form>
Copy the code

4. Implementation effect

(7) Ending

If there is any deficiency in the article, you are welcome to leave a message to exchange, thank friends for their support!

If it helps you, follow me! If you prefer the way of reading articles on wechat, you can follow my official account

We don’t know each other here, but we are working hard for our dreams

A adhere to push original development of technical articles of the public number: ideal more than two days