侧边栏壁纸
博主头像
coydone博主等级

记录学习,分享生活的个人站点

  • 累计撰写 306 篇文章
  • 累计创建 51 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

视图解析与模板引擎

coydone
2022-04-06 / 0 评论 / 0 点赞 / 340 阅读 / 7,251 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-04-24,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

视图解析:SpringBoot默认不支持 JSP,需要引入第三方模板引擎技术实现页面渲染。

视图解析的处理方式有:转发、重定向、自定义视图。

视图解析原理流程

1、目标方法处理的过程中,所有数据都会被放在 ModelAndViewContainer 里面。包括数据和视图地址。

2、方法的参数是一个自定义类型对象(从请求参数中确定的),把他重新放在 ModelAndViewContainer。

3、任何目标方法执行完成以后都会返回 ModelAndView(数据和视图地址)。

4、processDispatchResult 处理派发结果(页面该如何响应)

  • 1、render(mv, request, response); 进行页面渲染逻辑。

    • 1、根据方法的String返回值得到 View 对象【定义了页面的渲染逻辑】。

      • 1、所有的视图解析器尝试是否能根据当前返回值得到View对象。

      • 2、得到了 redirect:/main.html → Thymeleaf new RedirectView()。

      • 3、ContentNegotiationViewResolver 里面包含了下面所有的视图解析器,内部还是利用下面所有视图解析器得到视图对象。

      • 4、view.render(mv.getModelInternal(), request, response); 视图对象调用自定义的render进行页面渲染工作

        • RedirectView 如何渲染【重定向到一个页面】

        • 1、获取目标url地址

        • 2、response.sendRedirect(encodedURL);

视图解析:

  • 返回值以 forward: 开始: new InternalResourceView(forwardUrl); → 转发request.getRequestDispatcher(path).forward(request, response);

  • 返回值以 redirect: 开始: new RedirectView() → redirect就是重定向

  • 返回值是普通字符串: new ThymeleafView()

Thymeleaf

引入

前端交给我们的页面,是HTML页面。如果是我们以前开发,我们需要把他们转成JSP页面,JSP好处就是当我们查出一些数据转发到JSP页面以后,我们可以用JSP轻松实现数据的显示,及交互等。

JSP支持非常强大的功能,包括能写Java代码,但是SpringBoot项目是以jar的方式,不是war,我们用的还是嵌入式的Tomcat,所以默认是不支持JSP的。

那不支持JSP,如果我们直接用纯静态页面的方式,那给我们开发会带来非常大的麻烦,于是SpringBoot推荐你可以来使用模板引擎。

模板引擎,我们其实大家听到很多,其实JSP就是一个模板引擎,还有用的比较多的freemarker,Velocity,包括SpringBoot给我们推荐的Thymeleaf,模板引擎有非常多,但再多的模板引擎,他们的思想都是一样的。

模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢?就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是JSP还是其他模板引擎,都是这个思想。只不过不同模板引擎之间,他们可能这个语法有点不一样。

SpringBoot推荐的Thymeleaf模板引擎,它的语法更简单、功能更强大。

Thymeleaf介绍

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。Spring Boot推荐使用Thymeleaf、Freemarker等后现代的模板引擎技术;一但导入相关依赖,会自动配置ThymeleafAutoConfiguration、FreeMarkerAutoConfiguration。

引入Thymeleaf

在pom文件中引入thymeleaf启动器

<properties>
	<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    <!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 -->
    <!-- thymeleaf2 layout1 -->
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
<dependencys>
    <!--引入thymeleaf模块-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
</dependencys>

Thymeleaf的使用

只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染。

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";//默认前缀
    public static final String DEFAULT_SUFFIX = ".html";//默认后缀
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";//前缀
    private String suffix = ".html";//后缀
    private String mode = "HTML";
 	//......
}

测试

在java包下新建controller包写一个Controller。

package com.coydone.controller;

@Controller
public class HelloController {
    @RequestMapping("/success")
    public String success(){
        //classpath:/templates/success.html
        return "success";
    }
}

在rescources/templates下写一个success.html页面。

在浏览器中输入localhost:8080/success即可访问success.html页面。

在页面中展示数据

1、编写controller类

//查出一些数据,在页面展示
@RequestMapping("/success")
public String success(Map<String,Object> map){
    map.put("hello","你好");
    return "success";
}

2、导入thymeleaf的名称空间(会有提示功能)

<html lang="en" xmlns:th="http://www.thymeleaf.org">

3、使用thymeleaf语法写success.html页面,浏览器访问localhost:8080/success。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>成功!</h1>
    <!--th:text 将div里面的文本内容设置为 -->
    <div th:text="${hello}">这是显示欢迎信息</div>
</body>
</html>

基本语法

1、th:text,改变当前元素里面的文本内容;th:任意html属性;来替换原生属性的值。

2、表达式

Simple expressions:(表达式语法)
    Variable Expressions: ${...}:获取变量值;OGNL;
    	1)、获取对象的属性、调用方法
    	2)、使用内置的基本对象:
    		#ctx : context对象
    		#vars:context变量
            #locale : 国际化对象
            #request : (only in Web Contexts)HttpServletRequest对象
            #response : (only in Web Contexts)HttpServletResponse对象
            #session : (only in Web Contexts)HttpSession对象
            #servletContext : (only in Web Contexts)ServletContext对象
            ${session.foo}
        3)、内置的一些工具对象:
            #execInfo : 正在处理的模板信息
            #messages : 在变量表达式中获取外部消息的方法,与使用#{…}语法获得这些消息的方法相同。
            #uris : 转义部分URLs/URIs的方法
            #conversions : 执行配置的转换服务(如果有)的方法。
            #dates : java.util.Date对象方法:格式化、组件提取等。
            #calendars :类似于#dates , 但是是java.util.Calendar对象
            #numbers : 格式化数字对象的方法
            #strings:字符串对象方法:contains、startsWith、prepending/appending等。
            #objects : 对象的一般方法
            #bools : 布尔求值方法。
            #arrays : array方法
            #lists : list方法
            #sets : set集合方法
            #maps : map集合方法
            #aggregates : 在数组或集合上创建聚合的方法。
            #ids : 处理可能重复的id属性的方法(例如,作为迭代的结果)。

    Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
    	补充:配合 th:object="${session.user}:
        <div th:object="${session.user}">
            <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
            <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
            <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
        </div>
    
    Message Expressions: #{...}:获取国际化内容
    Link URL Expressions: @{...}:定义URL;
    		@{/order/process(execId=${execId},execType='FAST')}
    Fragment Expressions: ~{...}:片段引用表达式
    		<div th:insert="~{commons :: main}">...</div>
    		
Literals(字面量)
      Text literals: 'one text' , 'Another one!' ,…
      Number literals: 0 , 34 , 3.0 , 12.3 ,…
      Boolean literals: true , false
      Null literal: null
      Literal tokens: one , sometext , main ,…
Text operations:(文本操作)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
Arithmetic operations:(数学运算)
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
Boolean operations:(布尔运算)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
Comparisons and equality:(比较运算)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
Conditional operators:条件运算(三元运算符)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
Special tokens:特殊操作
    No-Operation: _ 

语法测试:

controller/HelloController.java

//查出一些数据,在页面展示
@RequestMapping("/success")
public String success(Map<String,Object> map){
    map.put("hello","<h1>你好</h1>");
    map.put("users", Arrays.asList("张三","李四","王五"));
    return "success";
}

rescources/templates/success.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>success,这是成功页面</h1>
        <div  id="div01" th:text="${hello}" th:id="${hello}"></div>
        <hr />
        <div th:text="${hello}"></div>
        <div th:utext="${hello}"></div>
        <hr />
        <!--th:each每次遍历都会生成当前这个标签:3个h2-->
        <h2 th:text="${user}" th:each="user:${users}"></h2>
        <hr />
        <div>
            <!-- 行内写法 [[]] 表示th:text     [()] 表示th:utext  -->
            <h3 th:each="user:${users}">[[${user}]]</h3>
        </div>
    </body>
</html>

运行结果:

0

评论区