SpringBoot之Thymeleaf实例

在SpringBoot的基础之上引入pom文件

  	    
            org.springframework.boot
            spring-boot-starter-thymeleaf
         

	     
            org.projectlombok
            lombok
            true
         
		
	     
             org.springframework.boot 
             spring-boot-configuration-processor 
             true 
         

设置application.properties

#端口号
server.port=7777

#thymeleaf
spring.thymeleaf.cache=false

#编码
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8

#全局变量
user.name=nemo
user.age=27

创建book.properties

book.name=犯罪嫌疑人X的献身
book.author=东野圭吾
book.price=38.3

创建book的实体类

package com.etoak.entity.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
//指定配置文件
@PropertySource(value = "classpath:book.properties")
@ConfigurationProperties(prefix = "book")
@Data
public class BookPropertiesEntity {
    private String name;
    private String author;
    private double price;
}

创建Controller

package com.etoak.controller.thymeleaf;

import com.etoak.entity.properties.BookPropertiesEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ThymeleafController {

    @Value("${user.name}")
    private String username;

    @Value("${user.age}")
    private String userage;

    @Autowired
    BookPropertiesEntity book;

    @RequestMapping("/thymeleafDemo")
    public String thymeleafDemo(Model model){

        List list = new ArrayList<>();
        list.add(book);

        BookPropertiesEntity book2 = new BookPropertiesEntity();
        book2.setName("刺杀骑士团长");
        book2.setAuthor("村上春树");
        book2.setPrice(65.00);

        BookPropertiesEntity book3 = new BookPropertiesEntity();
        book3.setName("三体");
        book3.setAuthor("刘慈欣");
        book3.setPrice(62.80);

        list.add(book2);
        list.add(book3);
        
        model.addAttribute("username",username);
        model.addAttribute("userage",userage);
        model.addAttribute("book",book);
        model.addAttribute("list",list);
        return "thymeleafDemo/thymeleafDemo";
    }
}

书写Thymeleaf页面




    
    
    
    thymeleafDemo
    
    



    

Demo

全局变量

遍历

  • 判断

  • 资源文件目录
    SpringBoot之Thymeleaf实例_第1张图片

    启动项目,浏览器输入http://localhost:7777/thymeleafDemo效果如下
    SpringBoot之Thymeleaf实例_第2张图片

    你可能感兴趣的:(SpringBoot)