012 expression for springboot thymeleaf

Posted by bearqst on Tue, 08 Feb 2022 05:09:44 +0100

1. Create module

1.1 create SpringBoot web project and use template engine

  • 1. Create module
    018-springboot-thymeleaf-expression

  • Introducing web and template engine

  • After creation, POM The XML file will have the following dependent coordinates
		<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>

1.2 in application Set the thymeleaf parameter in properties

#Configure and turn off template caching
spring.thymeleaf.cache=false
#Set thymeleaf template prefix
spring.thymeleaf.prefix=classpath:/templates/
#Set thymeleaf template suffix
spring.thymeleaf.suffix=.html

1.3 create entity class User

package com.zzy.springboot.pojo;


public class User {

    private Integer id;
    private String name;
    private String phone;
    private String address;

    public User() {
    }

    public User(Integer id, String name, String phone, String address) {
        this.id = id;
        this.name = name;
        this.phone = phone;
        this.address = address;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

1.4 create ThymeleafController

package com.zzy.springboot.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ThymeleafController {

    @RequestMapping(value = "/thymeleaf/index")
    public String index(Model model){
        model.addAttribute("data", "thymeleaf expression");
        return "index";
    }
}

1.5 create index in src/main/resources/templates HTML page

  • Introduce the namespace of thymeleaf
  • Note: th:text = "" is an attribute of Thymeleaf, which is used to display text
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <span th:text="${data}"></span>
</body>
</html>

1.6 operation access


http://localhost:8018/thymeleaf/index

2.thymeleaf - standard variable expression

2.1 grammar

      ${...}

2.2 description

The standard variable expression is used to access variables in the context of container (tomcat), and its function is the same as ${} in EL.
The variable expression in Thymeleaf uses ${variable name} to obtain the data in the model in the Controller

2.3 case display

Create a method to store the user information in the model, and the thymeleaf template page obtains the object information

2.3.1. Add method in ThymeleafController and put user object into model

    /**
     * model Object stored in
     * @param model
     * @return
     */
    @RequestMapping(value = "/thymeleaf/user")
    public String user(Model model){
        User user = new User();
        user.setId(1);
        user.setName("tom");
        user.setPhone("12333");
        user.setAddress("Dongcheng District ");
        model.addAttribute("user", user);
        return "user";
    }

2.3.2 create user under templates html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>thymeleaf Standard expression: displays object user information</title>
</head>
<body>
    <h1>Display user information</h1>
    User number:<span th:text="${user.id}"></span>
    User name:<span th:text="${user.name}"></span>
    User telephone:<span th:text="${user.phone}"></span>
    User address:<span th:text="${user.address}"></span>
</body>
</html>

2.3.3 browser access test

http://localhost:8018/thymeleaf/user

3. Expression - thyme3

3.1 grammar

      *{...}

3.2 description

  • Select a variable expression, also known as an asterisk variable expression, and use the th:object attribute to bind objects
  • The selection expression first uses th:object to bind the User object passed from the background, and then uses * to represent this object. The value in {} is the attribute in this object.
  • The selection variable expression * {...} is another method similar to the standard variable expression ${...} to represent variables
  • Selection variable expressions are solved on the selected object during execution, while ${...} is solved on the variable Model of the context. This writing method is more cumbersome than standard variable expressions

3.3 case display

3.3.1 in user HTML gets user data by selecting variable expressions (asterisk expressions)

  • Display User information
 <h1>Display user information: thymeleaf Select variable expression</h1>
    <h2>>Exhibition User User information (asterisk expression),Only in div Range valid):</h2>
    <div th:object="${user}">
        User number:<span th:text="*{id}"></span><br>
        User name:<span th:text="*{name}"></span><br>
        User telephone:<span th:text="*{phone}"></span><br>
        User address:<span th:text="*{address}"></span><br>
    </div>

3.3.3 operation access

http://localhost:8018/thymeleaf/user

4. thymeleaf standard variable expression and selection variable expression are mixed

  • In user HTML obtains user data through standard variable expression and selection variable expression
<h1>Display user information: thymeleaf Mixed use of standard variable expression and selection variable expression</h1>
    User number:*{user.id} ==> <span th:text="*{user.id}"></span><br/>
    User name:*{user.name} ==> <span th:text="*{user.name}"></span><br/>
    User mobile number:*{user.phone} ==> <span th:text="*{user.phone}"></span><br/>
    User address:*{user.address} ==> <span th:text="*{user.address}"></span><br/>

5.thymeleaf - URL expression

5.1 syntax:

             @{...}

5.2 description

It is mainly used to display links and addresses, and to dynamically obtain data in the URL path. It is mainly used for the following tags
< script src="...">,
< link href="...">,
< a href="...">,
< form action="...">,
< img src="">

5.3 case display

5.3.1 create module

019-springboot-thymeleaf-urlexpression

5.3.2 editing core configuration files

#\u8BBE\u7F6Etomcat\u5185\u5D4C\u7AEF\u53E3\u53F7
server.port=8019

#\u914D\u7F6E\u5173\u95ED\u6A21\u677F\u7F13\u5B58
spring.thymeleaf.cache=false
#\u8BBE\u7F6Ethymeleaf\u6A21\u677F\u524D\u7F00
spring.thymeleaf.prefix=classpath:/templates/
#\u8BBE\u7F6Ethymeleaf\u6A21\u677F\u540E\u7F00
spring.thymeleaf.suffix=.html

5.3.3 compiling pojo

package com.zzy.springboot.pojo;

public class User {
    private Integer id;
    private String username;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                '}';
    }

    public User() {
    }

    public User(Integer id, String username) {
        this.id = id;
        this.username = username;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

5.3.4 writing Controller

package com.zzy.springboot.web;

import com.zzy.springboot.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UrlThymeleafController {

    /*Get the data in mv with standard expression*/
    @RequestMapping("/user/index")
    public ModelAndView mv(){
        ModelAndView mv = new ModelAndView();
        User user = new User();
        user.setId(110);
        user.setUsername("Harris");
        mv.addObject("user", user);
        mv.setViewName("user");
        return mv;
    }


    /*Path expression @ {...}*/
    @RequestMapping("/user/url01")
    public String urlExpression(Model model){
        model.addAttribute("id", 111);
        model.addAttribute("username", "Shamet");
        return "url01";
    }

    /*Path expression @ {...} Parameter splicing*/
    @RequestMapping("/user/args")
    @ResponseBody
    public Object args(Integer id,String username){
        return "The user's number is:"+id+"The user's name is:"+username;
    }

    /*Path expression: restful style*/
    @RequestMapping("/user/restful1/{username}")
    @ResponseBody
    public Object festful1(@PathVariable String username){
        return "The user's name is:"+username;
    }

    @RequestMapping("/user/restful2/{id}/{username}")
    @ResponseBody
    public Object festful2(@PathVariable Integer id,
                           @PathVariable String username){
        return "The user's number is:"+id+"The user's name is:"+username;
    }

}

5.3.5 write user html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Standard variable expression ${...}obtain mv Data in</h1>
    User number:<span th:text="${user.id}"></span><br>
    User name:<span th:text="${user.username}"></span>
</body>
</html>

5.3.6 preparation url01 html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
<body>
    <h1>Traditional way</h1>
    <a href="http://www.baidu. Com "> jump to Baidu Homepage</a>
    <a href="http://Localhost: 8019 / user / index "> traditional method: jump to the user page</a>

    <h1>Path expression</h1>
    <a th:href="@{http://www.baidu. Com} "> path expression: jump to Baidu Homepage</a>
    <a th:href="@{http://Localhost: 8019 / user / index} "> path expression: jump to the user page</a>

    <h1>Path expression-Relative path (commonly used in development)</h1>
    <a th:href="@{/user/index}">Relative path: jump to:/user/index of user page</a>

    <h1>Path expressions: splicing of parameters</h1>
    <a th:href="@{/user/args?id=112&username=tom}">Path expression:? No. splicing parameters</a>

    <h1>Road strength expression: get background data as parameters</h1>
    <a th:href="@{'/user/args?id='+${id}+'&username='+${username}}">Background data,? No. splice as parameter</a><br>
    <a th:href="@{/user/args(id=${id},username=${username})}">As object data, background data</a><br>

    <h1>Path expression: get background data restFul Style parameter transfer</h1>
    <a th:href="@{'/user/restful1/'+${username}}">restful Single parameter transfer</a><br>
    <a th:href="@{'/user/restful2/'+${id}+'/'+${username}}">restful Multiple parameter passing</a><br>
</body>
</html>

5.3.7 operation access

  • function

  • Access path
    http://localhost:8019/user/url01

Topics: Java Spring Boot