• 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比较严格,如果标签取不到值就会报错。

    常见的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不推荐使用内置对象。

  • 相关阅读:
    SQL SELECT INTO 语句
    跨站脚本攻击测试[转]
    Visual Studio 2008中如何比较二个数据库的架构【Schema】和数据【Data】并同步 [转贴]
    联表UPDATE
    网站架构策划方案
    概念模型 逻辑模型 物理模型 区别
    Repeater嵌套绑定Repeater
    .net 2.0升级到了.net 3.5,开发工具从vs2005转为vs2008
    你必须知道的C#的25个基础概念(附演示) 【转】
    window2003中,在IIS中,如何解决不能播放.FLV文件
  • 原文地址:https://www.cnblogs.com/Code-Handling/p/12039117.html
Copyright © 2020-2023  润新知