springboot中的thymeleaf中的表达式(标准变量表达式和选择变量)


springboot中的thymeleaf的变量表达式有两种,一种是标准变量表达式,一种是选择变量表达式(不推荐使用)。

先建一个类,这里我用的是ModelAndView,viewname设置的是"show"。

package com.example.control;

import com.example.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MyController {

    @RequestMapping("/hehe")
    public ModelAndView hehe(){
        User user=new User();
        user.setId(1001);
        user.setUsername("zhang san");
        user.setAge(23);
        ModelAndView mv=new ModelAndView();
        mv.setViewName("show");
        mv.addObject("user",user);
        return mv;
    }
}

创建类以后,再建一个名为"show.html"的页面文件。

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<h1>用户的信息:h1>
<h3>用户编号:<em th:text="${user.getId()}">em>  
    用户名:<span th:text="${user.getUsername()}">span>  
    用户年纪:<em th:text="${user.getAge()}">em>
h3>
<h1>选择变量表达式(星号表达式):*{}(不推荐)h1>

<div th:object="${user}" >
    用户编号:<span th:text="*{getId()}">span>    
    用户性名:<span th:text="*{getUsername()}">span>    
    用户年龄:<span th:text="*{getAge()}">span>
div>

<h1>标签变量表达式与选择变量表达式的混合使用(这种用法不推荐)h1>
用户编号:<span th:text="*{user.getId()}">span>    
用户性名:<span th:text="*{user.username}">span>    
用户年龄:<span th:text="*{user.getAge()}">span>
body>
html>

运行就可以了!不过,*号表达式是不推荐使用的,因为很混乱。