Web MVC 视图应用

模版引擎

新一代服务端模版引擎

参考资源:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

模版类型

  • HTML
  • XML
  • TEXT
  • JAVASCRIPT
  • CSS
  • RAW

Thymeleaf 语法

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Good Thymes Virtual Grocery</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all"
          href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
  </head>
  <body>
    <p th:text="#{home.welcome}">Welcome to our grocery store!</p>
  </body>
</html>

核心要素

资源定位(模版来源)
  • 通用资源抽象
    • 文件资源:File
    • ClassPath资源:ClassLoader
    • 统一资源:URL
    • Web资源:ServletContext
  • Spring 资源抽象
    • Spring 资源:Resource
渲染上下文(变量来源)
  • 不同的实现
    • Context:Thymeleaf渲染上下文
    • Model:SpringWeb MVC模型
    • Attribute:Servlet上下文
模版引擎(模版渲染)
  • ITemplateEngine 实现

    • TemplateEngine :Thymeleaf 原生实现

    • SpringTemplateEngine :Spring 实现

      // 构建引擎
      SpringTemplateEngine templateEngine = new SpringTemplateEngine(); // 创建渲染上下文
      Context context = new Context();
      context.setVariable("message", "Hello,World");
      // 模板的内容
      String content = "<p th:text=\"${message}\">!!!</p>";
      // 渲染(处理)结果
      String result = templateEngine.process(content, context);
      // 输出渲染(处理)结果
      System.out.println(result);
      
      
    • SpringWebFluxTemplateEngine:Spring WebFlux实现

视图处理

Spring Web MVC 视图组件

  • ViewResolver:视图解析器
  • View:视图组件
  • DispatchServlet:总控

Thymeleaf 整合Spring Web MVC

  • ViewResolver:ThymeleafViewResolver
  • View:ThymeleafView
  • ITemplateEngine:SpringTemplateEngine

交互流程

示例:多视图处理器并存

  • 视图处理器
    • ThymeleafViewResolver
    • InternalResourceViewResolver
  • 目的
    • 理解ViewResolver Order
    • 理解ViewResolver 模版资源查找
    • 自定义ViewResolver Order
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容