SpringBoot3---核心特性---2、Web开发III(模板引擎、国际化、错误处理)

简介: SpringBoot3---核心特性---2、Web开发III(模板引擎、国际化、错误处理)

                                                                                 

                       星光下的赶路人star的个人主页

                      知世故而不世故 是善良的成熟


文章目录



1、模板引擎


  • 由于SpringBoot使用了嵌入式Servlet容器。所以JSP默认是不能使用的。
  • 如果需要服务端页面渲染,优先考虑使用模板引擎。


模板引擎页面默认放在src/main/resources/templates

SpringBoot包含以下模板引擎的自动配置

  • FreeMarker
  • Groovy
  • Thymeleaf
  • Mustache

Thymeleaf官网:https://www.thymeleaf.org/

<!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" th:href="@{/css/gtvg.css}" />
</head>
<body>
  <p th:text="#{home.welcome}">Welcome to our grocery store!</p>
</body
</html>

1.1 Thymeleaf


导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

自动配置原理

1、开启了org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration 自动配置。

2、属性绑定在ThymeleafProperties中,对应配置文件spring.thymeleaf内容

3、所以的模板页面默认在classpath:/templates文件夹下

4、默认效果

a、所有的模板页面在/classpath:/templates/下面找

b、找后缀名为.html的页面


1.2 基础语法


1、核心用法

th:xxx:动态渲染指定的html标签属性值、或者th指令(遍历、判断等)

  • th:text:标签体内文本值渲染
  • thutext:不会转义,显示为html原本的样子
  • th:属性:标签指定属性渲染
  • th:attr:标签任意属性渲染
  • th:if、th:each、…:其他th指令
  • 例如
<p th:text="${content}">原内容</p>
<a th:href="${url}">登录</a>
<img src="../../images/gtvglogo.png" 
     th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

表达式:用来动态取值

${}:变量取值:使用model共享给页面的值都直接用${}

@{}:url路径

#{}:国际化消息

~{}:片段引用

*{}:变量选择:需要配置th:object不到对象

系统工具&内置对象:详细文档

● param:请求参数对象

● session:session对象

● application:application对象

● #execInfo:模板执行信息

● #messages:国际化消息

● #uris:uri/url工具

● #conversions:类型转换工具

● #dates:日期工具,是java.util.Date对象的工具类

● #calendars:类似#dates,只不过是java.util.Calendar对象的工具类

● #temporals: JDK8+ java.time API 工具类

● #numbers:数字操作工具

● #strings:字符串操作

● #objects:对象操作

● #bools:bool操作

● #arrays:array工具

● #lists:list工具

● #sets:set工具

● #maps:map工具

● #aggregates:集合聚合工具(sum、avg)

● #ids:id生成工具


2、语法示例

表达式:

变量取值:${…}

url取值:@{…}

国际化消息:#{…}

变量选择:*{…}

片段引用:~{…}

常见:

文本:‘one text’,‘another one’…

数字:0,34,…

布尔:true,false

null:null

变量名:one,sometext,main,…

文本操作:

拼串:+

文本替换:|The name is ${name}|

布尔操作

二进制运算:and,or

取反:!,not

比较运算

比较:>,<,<=,>=(gt,lt,ge,le)

等值运算:=,!=

条件运算

if-then :(if)?(then)

if-then-else:(if)?(then):(else)

特殊操作

无操作

所有以上都可以嵌套组合

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
• 1

1.3 属性设置


th:href=“@{/product/list}”

th:attr=“class=${active}”

th:attr=“src=@{/images/gtvglogo.png},title=${logo},alt=#{logo}”

th:checked=“${user.active}”

<p th:text="${content}">原内容</p>
<a th:href="${url}">登录</a>
<img src="../../images/gtvglogo.png" 
     th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />


1.4 遍历


语法:th:each=“元素名,迭代状态:${集合}”

<tr th:each="prod : ${prods}">
  <td th:text="${prod.name}">Onions</td>
  <td th:text="${prod.price}">2.41</td>
  <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
  <td th:text="${prod.name}">Onions</td>
  <td th:text="${prod.price}">2.41</td>
  <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

iterStat有以下属性:

● ndex:当前遍历元素的索引,从0开始

● count:当前遍历元素的索引,从1开始

● size:需要遍历元素的总数量

● current:当前正在遍历的元素对象

● even/odd:是否偶数/奇数行

● first:是否第一个元素

● last:是否最后一个元素


1.5 判断


th:if

<a
  href="comments.html"
  th:href="@{/product/comments(prodId=${prod.id})}"
  th:if="${not #lists.isEmpty(prod.comments)}"
  >view</a

th:switch

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

1.6 属性优先级


  • 判断
  • 遍历
  • 判断
<ul>
  <li th:each="item : ${items}" th:text="${item.description}">Item description here...</li>
</ul>
• 1
• 2
• 3

Order Feature Attributes

1 片段包含 th:insert th:replace

2 遍历 th:each

3 判断 th:if th:unless th:switch th:case

4 定义本地变量 th:object th:with

5 通用方式属性修改 th:attr th:attrprepend th:attrappend

6 指定属性修改 th:value th:href th:src …

7 文本值 th:text th:utext

8 片段指定 th:fragment

9 片段移除 th:remove


1.7 行内写法


[[…]] or [(…)]

<p>Hello, [[${session.user.name}]]!</p>
• 1

1.8 变量选择


<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>

等同于

<div>
  <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
  <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
  <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div

1.9 模板布局


  • 定义模板:th:fragment
  • 引用模板:~{templatename::selector}
  • 插入模板:th:insert、th:replace
<footer th:fragment="copy">&copy; 2011 The Good Thymes Virtual Grocery</footer>
<body>
  <div th:insert="~{footer :: copy}"></div>
  <div th:replace="~{footer :: copy}"></div>
</body>
<body>
  结果:
  <body>
    <div>
      <footer>&copy; 2011 The Good Thymes Virtual Grocery</footer>
    </div>
    <footer>&copy; 2011 The Good Thymes Virtual Grocery</footer>
  </body>
</body>

1.10 devtools


      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
      </dependency>

修改页面后;ctrl+F9刷新效果;

java代码的修改,如果devtools热启动了,可能会引起一些bug,难以排查


2、国家化


国际化的自动配置参照MessageSourceAutoConfiguration


实现步骤:

1、Spring Boot在类路径根下查找messages资源绑定文件。文件名为:message.properties.

2、多语言可以定义多个消息文件,命名为message_区域代码.properties。如:

messages.properties:默认

messages_zh_CN.properties:中文环境

messages_en_US.properties:英文环境

3、在程序中自动注入MessageSource组件,获取国际化的配置项值

4、在页面中可以使用表达式#{}获取国际化的配置项值

    @Autowired  //国际化取消息用的组件
    MessageSource messageSource;
    @GetMapping("/haha")
    public String haha(HttpServletRequest request){
        Locale locale = request.getLocale();
        //利用代码的方式获取国际化配置文件中指定的配置项的值
        String login = messageSource.getMessage("login", null, locale);
        return login;
    }

3、错误处理


3.1 默认机制


错误处理的自动配置都在ErrorMvcAutoConfiguration中,两大核心机制:

  • SpringBoot会自适应处理错误,响应页面或JSON数据
  • SpringMVC的错位处理机制依然保留,MVC处理不了,才会交给Boot进行处理

  • 发送错误以后,转发给/error路径,SpringBoot在底层写好应该BasicErrorController,专门处理这个请求
  @RequestMapping(produces = MediaType.TEXT_HTML_VALUE) //返回HTML
  public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
    HttpStatus status = getStatus(request);
    Map<String, Object> model = Collections
      .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
    response.setStatus(status.value());
    ModelAndView modelAndView = resolveErrorView(request, response, status, model);
    return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
  }
  @RequestMapping  //返回 ResponseEntity, JSON
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
    HttpStatus status = getStatus(request);
    if (status == HttpStatus.NO_CONTENT) {
      return new ResponseEntity<>(status);
    }
    Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
    return new ResponseEntity<>(body, status);
  }
  • 错误页面是这么解析的
//1、解析错误的自定义视图地址
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
//2、如果解析不到错误页面的地址,默认的错误页就是 error
return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);

容器中专门有一个错误视图解析器

@Bean
@ConditionalOnBean(DispatcherServlet.class)
@ConditionalOnMissingBean(ErrorViewResolver.class)
DefaultErrorViewResolver conventionErrorViewResolver() {
    return new DefaultErrorViewResolver(this.applicationContext, this.resources);
}

SpringBoot解析自定义错误页的默认规则

  @Override
  public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
    ModelAndView modelAndView = resolve(String.valueOf(status.value()), model);
    if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
      modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
    }
    return modelAndView;
  }
  private ModelAndView resolve(String viewName, Map<String, Object> model) {
    String errorViewName = "error/" + viewName;
    TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName,
        this.applicationContext);
    if (provider != null) {
      return new ModelAndView(errorViewName, model);
    }
    return resolveResource(errorViewName, model);
  }
  private ModelAndView resolveResource(String viewName, Map<String, Object> model) {
    for (String location : this.resources.getStaticLocations()) {
      try {
        Resource resource = this.applicationContext.getResource(location);
        resource = resource.createRelative(viewName + ".html");
        if (resource.exists()) {
          return new ModelAndView(new HtmlResourceView(resource), model);
        }
      }
      catch (Exception ex) {
      }
    }
    return null;
  }

容器中有一个默认的名为error的view;提供了默认白页功能

@Bean(name = "error")
@ConditionalOnMissingBean(name = "error")
public View defaultErrorView() {
    return this.defaultErrorView;
}

封装了JSON格式的错误信息

  @Bean
  @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
  public DefaultErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes();
  }

规则:

1、解析一个错误页

(1)如果发生了500、404、503、403这些错误


如果有模板引擎,默认在classpath:/templates/error/精确码.html

如果没有模板引擎,在静态资源文件夹下找精确码.html

(2)如果匹配不到精确码.html这些精确的错误页,就去找5xx.html,4xx.html模糊匹配

如果有模板引擎,默认在classpath:/template/error/5xx.html

如果没有模板引擎,在静态资源目录下找5xx.html

2、如果模板引擎路径templates下有error.html页面,就直接去渲染


3.2 自定义错误响应


1、自定义json响应

使用@ControllerAdvice+@ExceptionHandler进行统一异常处理

2、自定义页面响应

根据boot的错误页面规则,自定义页面模板


3.3 最佳实战


前后分离

后台发生的所有错误,@ControllerAdvice+@Exceptionhandler进行统一异常处理

服务端页面渲染

不可预知的一些,HTTP码表示的服务器或客户端错误

给classpath:/templates/error/下面,放常用精确的错误码页面。500.html,404.html

发生业务错误

核心业务,每一种错误,都应该代码控制,跳转到自己定制的错误页

通用业务,classpath:/templates/error.html页面,显示错误信息

页面,JSON,可用的Model数据如下

                                                                                     

                                                                        您的支持是我创作的无限动力

                                                                                     

                      希望我能为您的未来尽绵薄之力

                                                                                     

                    如有错误,谢谢指正若有收获,谢谢赞美


相关文章
|
6月前
|
前端开发 Java 数据库
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 介绍
本课介绍Spring Boot集成Thymeleaf模板引擎。Thymeleaf是一款现代服务器端Java模板引擎,支持Web和独立环境,可实现自然模板开发,便于团队协作。与传统JSP不同,Thymeleaf模板可以直接在浏览器中打开,方便前端人员查看静态原型。通过在HTML标签中添加扩展属性(如`th:text`),Thymeleaf能够在服务运行时动态替换内容,展示数据库中的数据,同时兼容静态页面展示,为开发带来灵活性和便利性。
316 0
|
2月前
|
缓存 JSON 前端开发
第07课:Spring Boot集成Thymeleaf模板引擎
第07课:Spring Boot集成Thymeleaf模板引擎
391 0
第07课:Spring Boot集成Thymeleaf模板引擎
|
4月前
|
Web App开发 前端开发 JavaScript
鸿蒙5开发宝藏案例分享---Web适配一多开发实践
这是一份实用的鸿蒙Web多设备适配开发指南,针对开发者在不同屏幕尺寸下的布局难题提供了解决方案。文章通过三大法宝(相对单位、媒体查询和窗口监听)详细介绍如何实现智能适配,并提供了多个实战案例,如宫格布局、对话框变形和自适应轮播图等。此外,还分享了调试技巧及工具推荐,帮助开发者快速上手并优化性能。最后鼓励读者实践探索,并提示更多官方资源等待发现。
|
6月前
|
关系型数据库 MySQL 数据库
基于Flink CDC 开发,支持Web-UI的实时KingBase 连接器,三大模式无缝切换,效率翻倍!
TIS 是一款基于Web-UI的开源大数据集成工具,通过与人大金仓Kingbase的深度整合,提供高效、灵活的实时数据集成方案。它支持增量数据监听和实时写入,兼容MySQL、PostgreSQL和Oracle模式,无需编写复杂脚本,操作简单直观,特别适合非专业开发人员使用。TIS率先实现了Kingbase CDC连接器的整合,成为业界首个开箱即用的Kingbase CDC数据同步解决方案,助力企业数字化转型。
1191 5
基于Flink CDC 开发,支持Web-UI的实时KingBase 连接器,三大模式无缝切换,效率翻倍!
|
6月前
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 的使用
本文介绍了 Thymeleaf 在 Spring Boot 项目中的使用方法,包括访问静态页面、处理对象和 List 数据、常用标签操作等内容。通过示例代码展示了如何配置 404 和 500 错误页面,以及如何在模板中渲染对象属性和列表数据。同时总结了常用的 Thymeleaf 标签,如 `th:value`、`th:if`、`th:each` 等,并提供了官方文档链接以供进一步学习。
473 0
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 的使用
|
6月前
|
机器学习/深度学习 开发框架 API
Python 高级编程与实战:深入理解 Web 开发与 API 设计
在前几篇文章中,我们探讨了 Python 的基础语法、面向对象编程、函数式编程、元编程、性能优化、调试技巧以及数据科学和机器学习。本文将深入探讨 Python 在 Web 开发和 API 设计中的应用,并通过实战项目帮助你掌握这些技术。
|
6月前
|
缓存 Java 应用服务中间件
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——依赖导入和Thymeleaf相关配置
在Spring Boot中使用Thymeleaf模板,需引入依赖`spring-boot-starter-thymeleaf`,并在HTML页面标签中声明`xmlns:th=&quot;http://www.thymeleaf.org&quot;`。此外,Thymeleaf默认开启页面缓存,开发时建议关闭缓存以实时查看更新效果,配置方式为`spring.thymeleaf.cache: false`。这可避免因缓存导致页面未及时刷新的问题。
259 0
|
8月前
|
移动开发 前端开发 JavaScript
SpringBoot3 整合Thymeleaf 模板引擎
Thymeleaf 是一个基于 Java 的现代模板引擎,支持 HTML 原型,文件后缀为 .html,可直接在浏览器中查看静态效果。它与 Spring Boot 完美整合,默认配置即可使用,无需额外视图解析器设置。Thymeleaf 支持多种表达式(如变量、链接、国际化等)和 th 属性(如 th:text、th:if 等),适用于 Web 和非 Web 应用开发。通过 th:fragment、th:insert、th:replace 和 th:include 等属性,可以抽取和复用公共页面片段,并支持参数传递。
1096 12
|
9月前
|
Java 开发者 微服务
Spring Boot 入门:简化 Java Web 开发的强大工具
Spring Boot 是一个开源的 Java 基础框架,用于创建独立、生产级别的基于Spring框架的应用程序。它旨在简化Spring应用的初始搭建以及开发过程。
317 7
Spring Boot 入门:简化 Java Web 开发的强大工具
|
9月前
|
前端开发 安全 JavaScript
2025年,Web3开发学习路线全指南
本文提供了一条针对Dapp应用开发的学习路线,涵盖了Web3领域的重要技术栈,如区块链基础、以太坊技术、Solidity编程、智能合约开发及安全、web3.js和ethers.js库的使用、Truffle框架等。文章首先分析了国内区块链企业的技术需求,随后详细介绍了每个技术点的学习资源和方法,旨在帮助初学者系统地掌握Dapp开发所需的知识和技能。
2025年,Web3开发学习路线全指南