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

本文涉及的产品
云解析 DNS,旗舰版 1个月
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
全局流量管理 GTM,标准版 1个月
简介: 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数据如下

                                                                                     

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

                                                                                     

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

                                                                                     

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


相关文章
|
3月前
|
开发框架 搜索推荐 数据可视化
Django框架适合开发哪种类型的Web应用程序?
Django 框架凭借其强大的功能、稳定性和可扩展性,几乎可以适应各种类型的 Web 应用程序开发需求。无论是简单的网站还是复杂的企业级系统,Django 都能提供可靠的支持,帮助开发者快速构建高质量的应用。同时,其活跃的社区和丰富的资源也为开发者在项目实施过程中提供了有力的保障。
159 62
|
2月前
|
Java 开发者 微服务
Spring Boot 入门:简化 Java Web 开发的强大工具
Spring Boot 是一个开源的 Java 基础框架,用于创建独立、生产级别的基于Spring框架的应用程序。它旨在简化Spring应用的初始搭建以及开发过程。
103 6
Spring Boot 入门:简化 Java Web 开发的强大工具
|
2月前
|
前端开发 安全 JavaScript
2025年,Web3开发学习路线全指南
本文提供了一条针对Dapp应用开发的学习路线,涵盖了Web3领域的重要技术栈,如区块链基础、以太坊技术、Solidity编程、智能合约开发及安全、web3.js和ethers.js库的使用、Truffle框架等。文章首先分析了国内区块链企业的技术需求,随后详细介绍了每个技术点的学习资源和方法,旨在帮助初学者系统地掌握Dapp开发所需的知识和技能。
2025年,Web3开发学习路线全指南
|
3月前
|
存储 前端开发 JavaScript
如何在项目中高效地进行 Web 组件化开发
高效地进行 Web 组件化开发需要从多个方面入手,通过明确目标、合理规划、规范开发、加强测试等一系列措施,实现组件的高效管理和利用,从而提高项目的整体开发效率和质量,为用户提供更好的体验。
55 7
|
3月前
|
开发框架 JavaScript 前端开发
TypeScript 是一种静态类型的编程语言,它扩展了 JavaScript,为 Web 开发带来了强大的类型系统、组件化开发支持、与主流框架的无缝集成、大型项目管理能力和提升开发体验等多方面优势
TypeScript 是一种静态类型的编程语言,它扩展了 JavaScript,为 Web 开发带来了强大的类型系统、组件化开发支持、与主流框架的无缝集成、大型项目管理能力和提升开发体验等多方面优势。通过明确的类型定义,TypeScript 能够在编码阶段发现潜在错误,提高代码质量;支持组件的清晰定义与复用,增强代码的可维护性;与 React、Vue 等框架结合,提供更佳的开发体验;适用于大型项目,优化代码结构和性能。随着 Web 技术的发展,TypeScript 的应用前景广阔,将继续引领 Web 开发的新趋势。
66 2
|
3月前
|
前端开发 API 开发者
Python Web开发者必看!AJAX、Fetch API实战技巧,让前后端交互如丝般顺滑!
在Web开发中,前后端的高效交互是提升用户体验的关键。本文通过一个基于Flask框架的博客系统实战案例,详细介绍了如何使用AJAX和Fetch API实现不刷新页面查看评论的功能。从后端路由设置到前端请求处理,全面展示了这两种技术的应用技巧,帮助Python Web开发者提升项目质量和开发效率。
88 1
|
3月前
|
XML 安全 PHP
PHP与SOAP Web服务开发:基础与进阶教程
本文介绍了PHP与SOAP Web服务的基础和进阶知识,涵盖SOAP的基本概念、PHP中的SoapServer和SoapClient类的使用方法,以及服务端和客户端的开发示例。此外,还探讨了安全性、性能优化等高级主题,帮助开发者掌握更高效的Web服务开发技巧。
|
3月前
|
XML Java 网络架构
使用 Spring Boot 公开 SOAP Web 服务端点:详细指南
使用 Spring Boot 公开 SOAP Web 服务端点:详细指南
169 0
|
4月前
|
XML JSON API
ServiceStack:不仅仅是一个高性能Web API和微服务框架,更是一站式解决方案——深入解析其多协议支持及简便开发流程,带您体验前所未有的.NET开发效率革命
【10月更文挑战第9天】ServiceStack 是一个高性能的 Web API 和微服务框架,支持 JSON、XML、CSV 等多种数据格式。它简化了 .NET 应用的开发流程,提供了直观的 RESTful 服务构建方式。ServiceStack 支持高并发请求和复杂业务逻辑,安装简单,通过 NuGet 包管理器即可快速集成。示例代码展示了如何创建一个返回当前日期的简单服务,包括定义请求和响应 DTO、实现服务逻辑、配置路由和宿主。ServiceStack 还支持 WebSocket、SignalR 等实时通信协议,具备自动验证、自动过滤器等丰富功能,适合快速搭建高性能、可扩展的服务端应用。
268 3
|
3月前
|
设计模式 前端开发 数据库
Python Web开发:Django框架下的全栈开发实战
【10月更文挑战第27天】本文介绍了Django框架在Python Web开发中的应用,涵盖了Django与Flask等框架的比较、项目结构、模型、视图、模板和URL配置等内容,并展示了实际代码示例,帮助读者快速掌握Django全栈开发的核心技术。
269 45

热门文章

最新文章

  • 1
    打造高效的Web Scraper:Python与Selenium的完美结合
    13
  • 2
    Burp Suite Professional 2025.2 (macOS, Linux, Windows) - Web 应用安全、测试和扫描
    26
  • 3
    AppSpider Pro 7.5.015 for Windows - Web 应用程序安全测试
    20
  • 4
    【02】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-2月12日优雅草简化Centos stream8安装zabbix7教程-本搭建教程非docker搭建教程-优雅草solution
    54
  • 5
    部署使用 CHAT-NEXT-WEB 基于 Deepseek
    342
  • 6
    【2025优雅草开源计划进行中01】-针对web前端开发初学者使用-优雅草科技官网-纯静态页面html+css+JavaScript可直接下载使用-开源-首页为优雅草吴银满工程师原创-优雅草卓伊凡发布
    26
  • 7
    java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
    40
  • 8
    零基础构建开源项目OpenIM桌面应用和pc web- Electron篇
    28
  • 9
    【01】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-硬件设备实时监控系统运营版发布-本产品基于企业级开源项目Zabbix深度二开-分步骤实现预计10篇合集-自营版
    22
  • 10
    FastAPI与Selenium:打造高效的Web数据抓取服务 —— 采集Pixabay中的图片及相关信息
    55