zoukankan      html  css  js  c++  java
  • 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不推荐使用内置对象。

  • 相关阅读:
    防盗链(三)nginx实现图片防盗链(referer指令)
    防盗链(二)nginx secure_link下载防盗链
    防盗链(一)资料整理
    如何实现 token 加密
    Socket编程(三)demo举例
    Socket编程-(二)tcp三次握手与四次挥手
    Spring的事务控制,注解和xml配置以及解释
    SpringAop的核心概念和使用,表达式匹配刨析,xml配置通知和环绕通知
    SpringAop的简介
    Spring整合JUnit测试单元
  • 原文地址:https://www.cnblogs.com/Code-Handling/p/12039117.html
Copyright © 2011-2022 走看看