美文网首页Spring-Boot我爱编程
2 springboot入门之 整合thymeleaf

2 springboot入门之 整合thymeleaf

作者: 半盏茶灯 | 来源:发表于2018-04-09 11:24 被阅读138次

前言:
thymeleaf 是由thyme [taɪm] (百里香) ,leaf[li:f] (叶子)两个单词组成.
thymeleaf 是java模版引擎,可以很好的和spring集成。

1. 引入依赖

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

2. application.properties中添加配置

spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.mode=HTML

注:
Spring Boot使用的Thymeleaf 3.0或者更高版本是配置:spring.thymeleaf.mode=HTML。
如果Thymeleaf 2.0版本的话配置:spring.thymeleaf.mode=HTML5。

3. 创建Controller ,和相应html。

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping(value = "/login")
    public String login() {
        return "/login";
    }
}

上面返回/login,即返回对应login.html,

<!DOCTYPE html>
<html lang="en" >
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
<H2>登录测试</H2>
</body>
</html>

如果页面需要使用thymeleaf需要添加命名空间xmlns:th="http://www.thymeleaf.org"

4.运行测试,访问'http://localhost:8080/user/login',效果如图:

1.png

5.后台用过模版引擎传递参数给页面

  • 后台添加参数。笔者在 在上面的UserController添加方法,并设置参数:
@RequestMapping(value = "/login2")
public String login2(ModelMap map) {
    Map<String, Object> userInfoMap = new HashMap<>();
    userInfoMap.put("name", "张三");
    userInfoMap.put("age", 24);

    SimpleVo vo = new SimpleVo();
    vo.setCode(1000);
    vo.setMessage("请求成功");

    map.put("userInfo", userInfoMap);
    map.put("vo", vo);

    return "/login2";
}
  • 对应login2.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>thymeleaf模版,带数据的</title>
</head>

用户名:<span th:text="${userInfo.name}"></span><br/>
年龄:<span th:text="${userInfo.age}"></span><p />

访问对象属性:<span th:text="${vo.code}"/> ,访问对象方法:<span th:text="${vo.getMessage()}"/><p />

<a th:href="@{/user/login}">相对路径页面测试</a><p/>
<a th:href="@{http://www.baidu.com}">据对路径测试(比如访问:百度)</a><p/>

</body>
</html>
  • 运行效果如图:


    2.png

相关文章

网友评论

    本文标题:2 springboot入门之 整合thymeleaf

    本文链接:https://www.haomeiwen.com/subject/suwbhftx.html