如何使用spring mvc访问百万美元模板中的变量

时间:2017-06-02 00:29:42

标签: spring-mvc thymeleaf

如何在百万富翁模板中访问我在Spring MVC中添加的模型变量?我有以下控制器代码:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[] = "05/09/2013";
    char *month = strtok(str, "/");
    char *day = strtok(0, "/");
    char *year = strtok(0, "/");

    printf("%s.%s.%s\n", day, month, year);
    return 0;
}

如何在百万富翁模板中访问变量var1,var5,var6等?

@Controller
public class ThymeLeafController {

    @GetMapping("/thyme")
    public void thymeleaf(ModelAndView modelAndView) {
        modelAndView.addObject("var1", "var1");
        modelAndView.addObject(Arrays.asList("var2", "var3", "var4"));
        modelAndView.getModel().put("var5", "var5");
        modelAndView.getModelMap().addAttribute("var6", "var6");
        modelAndView.getModelMap().addAttribute(Arrays.asList("var7", "var8", "var9"));

        modelAndView.setViewName("thymeleaf");
    }
}

1 个答案:

答案 0 :(得分:2)

行为:

访问属性取决于添加它们的位置。如果属性已添加到ModelAndView对象,则必须通过“$ {modelAndView.model.xxxx}”访问它们,其中xxxx是属性名称。如果将属性添加到Model对象,则只需使用属性名称“$ {attributeName}”即可访问它们。见下面的例子。

<强>控制器:

@GetMapping("/thyme")
public void thymeleaf(ModelAndView modelAndView, Model model) {
    modelAndView.addObject("var1", "var1");
    modelAndView.addObject(Arrays.asList("var2", "var3", "var4"));
    modelAndView.getModel().put("var5", "var5");
    modelAndView.getModelMap().addAttribute("var6", "var6");
    modelAndView.getModelMap().addAttribute(Arrays.asList("var7", "var8", "var9"));

    model.addAttribute("attribute1", "attributeValue1");

}

<强>模板:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Thymeleaf</title>
</head>
<body>
<div th:text="${attribute1}"></div>
<div th:text="${modelAndView.model}"></div>
<div th:text="${modelAndView.model.var1}"></div>
</body>
</html>

<强>输出:

attributeValue1
{var1=var1, stringList=[var7, var8, var9], var5=var5, var6=var6}
var1