springboot整合thymleaf模板引擎

thymeleaf作为springboot官方推荐使用的模板引擎,简单易上手,功能强大,thymeleaf的功能和jsp有许多相似之处,两者都属于服务器端渲染技术,但thymeleaf比jsp的功能更强大。

1. thymeleaf入门

1.1 引入坐标

<!--springBoot整合thymeleaf-->
<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

1.2 编写controller类

@GetMapping("/index")
    public String index(Model model){
        model.addAttribute("msg","hello");
        return "index";
    }

1.3 前端页面

页面中的html标签必须添加这个地址,否则无法使用thymeleaf,且html标签内只能写这个网址,如果添加其他网址,则会造成页面异常。

异常:

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<cite th:text="${msg}">王超</cite>

结果为cite标签里的内容“王超”被替换为hello.

th:text 是thymeleaf的语法之一,他的作用就是文本替换。不管标签内是否有内容,都会被替换成存储的内容。同时也要注意 thymeleaf比较严格,如果标签取不到值就会报错。

扫描二维码关注公众号,回复: 7987555 查看本文章

常见的thymeleaf便签如下:

 在实际开发中由于ModelAndView是request级别的,所以如果要在其他页面也展示数据,就需要使用session进行存储。最常见的就是登陆之后要在index页面展示用户信息。

2. thymeleaf使用session内置对象(不推荐)

2.1 controller类

HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
request.getSession().setAttribute("user", (SysUser)SecurityUtils.getSubject().getPrincipal());

2.2 前台页面

<cite th:text="${session.user.getUsername()}">王超</cite>

我登陆的账号名称是admin,所以标签内的王超会被替换为admin。如果用model的话是无法获取到username的值,页面会报错。

所以需要用session进行会话存储,但是thymeleaf不推荐使用内置对象。

猜你喜欢

转载自www.cnblogs.com/Code-Handling/p/11939063.html