Spring Boot整合Thymeleaf模板引擎

简介: Spring Boot整合Thymeleaf模板引擎

Spring Boot Web开发(一)


一、静态资源映射


(1)所有/webjars/**,都去classpath:/META_INF/resources/webjars/找资源

webjars:以Jar包的方式引入静态资源https://www.webjars.org/

    <!--引入jquery-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.1.1</version>
        </dependency>

20191231205735983.png

启动SpringApplication主程序,访问localhost:8080/webjars/jquery/3.3.1/jquery.js就能够访问到刚刚导入的静态资源了!


(2)/**访问当前项目的任何静态资源,静态资源可以放在以下的目录下:

classpath:/META_INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/:当前项目的根路径

(3)配置欢迎页面,静态资源文件夹下的所有index.html页面:被/映射如访问localhost:8080/



20191231211459326.png


20191231211517211.png

(4)所有的/favicon.ico都是在静态资源文件夹下找


二、Thymeleaf的使用


1.引入thymeleaf:

  <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
        <!--布局功能的支持程序 thymeleaf3主程序-->
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
    </properties>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.1.6.RELEASE</version>
    </dependency>

2.Thymeleaf使用和语法

(1)与SpringBoot的整合

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";
  static {
        DEFAULT_ENCODING = StandardCharsets.UTF_8;
    }

上述代码告诉我们,只需要将html页面放在类路径下的resources/templates/就可以使用thymeleaf模板引擎了。

20191231233452719.png

现在来编写一下Controller层的代码

package com.Zhonggger.springbootweb01.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
    @RequestMapping("/success")
    public String success(){
        //视图解析器,找寻classpath:/templates/success.html
        return "success";
    }
}


访问localhost:8080/success

出现下面的界面,证明Thymeleaf模板引擎整合成功


20191231233827268.png

首先,导入thymeleaf的名称空间


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


然后,可以使用thymeleaf的语法

前端:

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

后端:

package com.Zhonggger.springbootweb01.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
@Controller
public class HelloController {
    @RequestMapping("/success")
    public String success(Map<String,Object> map){
        //视图解析器,找寻classpath:/templates/success.html
        map.put("hello","你好");
        return "success";
    }
}

访问localhost:8080/success


2019123123483169.png

具体的语法就不在这里一一列举了,大家可以查看Thymeleaf的官方文档。


SpringMVC自动配置

https://docs.spring.io/spring-boot/docs/2.2.2.RELEASE/reference/htmlsingle/#boot-features-spring-mvc

Spr
ing MVC Auto-configuration
Spring Boot 自动配置好了Spring MVC
以下是Spring Boot对SpringMVC的自动配置
    1.自动配置了视图解析器:ContentNegotiatingViewResolver和BeanNameViewResolver
      视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染
    ContentNegotiatingViewResolver:自动组合所有的属兔解析器
    如何定制:可以自己给容器中添加一个视图解析器,自动将其组合起来。
package com.Zhonggger.springbootweb01;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import java.util.Locale;
@SpringBootApplication
public class Springbootweb01Application {
    public static void main(String[] args) {
        SpringApplication.run(Springbootweb01Application.class, args);
    }
  //往容器中添加一个新的视图解析器MyViewResolver
    @Bean
    public MyViewResolver getMyViewResolver(){
        return new MyViewResolver();
    }
    private static class MyViewResolver implements ViewResolver{
        @Override
        public View resolveViewName(String s, Locale locale) throws Exception {
            return null;
        }
    }
}


在DispatcherServlet.java中的doDispatch方法上打断点,用debug模式启动SpringBoot,在浏览器地址栏上输入localhost:8080/

可以在viewResolvers下找到刚刚加进容器的类:


2020010118382442.png

2.支持静态资源,包括WebJars
Support for serving static resources, including support for WebJars (covered later in this document)).
3.支持静态页面index.html
Static index.html support.
4.支持首页图标favicon.ico
Custom Favicon support (covered later in this document).
5.自动注册了 Converter、GenericConverter、Formatter
Automatic registration of Converter, GenericConverter, and Formatter beans.
Converter:转换器:public String hello(User user) 类型转换时使用
Formatter:格式化:2020-01-01 格式化为Date
自己添加的格式化器转换器,只需要放到容器中即可
6.Support for HttpMessageConverters (covered later in this document).
HttpMessageConverters:SpringMVC用来转换Http请求和响应的:User-json:
HttpMessageConverters是从容器中确定的;获取所有的HttpMessageConverter
自己给容器中添加HttpMessageConverter,就用@Bean注册进容器即可
7.用于定义错误代码生成规则的
Automatic registration of MessageCodesResolver (covered later in this document).
8.可以配置一个 ConfigurableWebBindingInitializer来替换默认的(添加到容器中)
初始化WebDataBinder:
  请求数据封装成JavaBean
Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).

拓展Spring MVC配置

编写一个配置类(@Configuration),是WebMvcConfigurer类型的,不能标注@EnableWebMvc

package com.Zhonggger.springbootweb01.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//使用WebMvcConfigurer可以扩展Spring MVC的配置
@Configuration
public class MyMVCConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //浏览器发送/zhongger请求,请求也可以来到success.html页面
        registry.addViewController("/zhongger").setViewName("success");
    }
}

全面接管Spring MVC

在@Configuration上在加@EnableWebMVC注解,所有都是我们自己配置

启动Spring Boot后,在地址栏输入:localhost:8080/zhongger,出现以下页面,则配置成功:

20200101232650220.png


总结:如何修改Spring Boot的默认配置


模式:


(1)SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component),如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;

(2)Spring Boot中会有很多xxxConfigure帮助我们进行扩展配置。

相关文章
|
7月前
|
前端开发 Java 数据库
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 介绍
本课介绍Spring Boot集成Thymeleaf模板引擎。Thymeleaf是一款现代服务器端Java模板引擎,支持Web和独立环境,可实现自然模板开发,便于团队协作。与传统JSP不同,Thymeleaf模板可以直接在浏览器中打开,方便前端人员查看静态原型。通过在HTML标签中添加扩展属性(如`th:text`),Thymeleaf能够在服务运行时动态替换内容,展示数据库中的数据,同时兼容静态页面展示,为开发带来灵活性和便利性。
326 0
|
6月前
|
前端开发 Java UED
从基础到进阶:Spring Boot + Thymeleaf 整合开发中的常见坑与界面优化
本文深入探讨了 **Spring Boot + Thymeleaf** 开发中常见的参数绑定问题与界面优化技巧。从基础的 Spring MVC 请求参数绑定机制出发,分析了 `MissingServletRequestParameterException` 的成因及解决方法,例如确保前后端参数名、类型一致,正确设置请求方式(GET/POST)。同时,通过实际案例展示了如何优化支付页面的视觉效果,借助简单的 CSS 样式提升用户体验。最后,提供了官方文档等学习资源,帮助开发者更高效地掌握相关技能。无论是初学者还是进阶用户,都能从中受益,轻松应对项目开发中的挑战。
228 0
|
3月前
|
缓存 JSON 前端开发
第07课:Spring Boot集成Thymeleaf模板引擎
第07课:Spring Boot集成Thymeleaf模板引擎
404 0
第07课:Spring Boot集成Thymeleaf模板引擎
|
7月前
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 的使用
本文介绍了 Thymeleaf 在 Spring Boot 项目中的使用方法,包括访问静态页面、处理对象和 List 数据、常用标签操作等内容。通过示例代码展示了如何配置 404 和 500 错误页面,以及如何在模板中渲染对象属性和列表数据。同时总结了常用的 Thymeleaf 标签,如 `th:value`、`th:if`、`th:each` 等,并提供了官方文档链接以供进一步学习。
485 0
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 的使用
|
7月前
|
缓存 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`。这可避免因缓存导致页面未及时刷新的问题。
283 0
|
前端开发 Java Spring
《精通Spring MVC 4》——2.4 使用Thymeleaf
对于Web设计人员来说,Thymeleaf有一项很大的优势,那就是在服务器没有运行的时候,模板中所有的动态内容都可以采用一个默认值。资源URL可以采用相对的路径来指定,每个标签都可以包含占位符。在前面的样例里面,如果是在应用的上下文中,那么文本“Hello html”将不会显示,但是如果直接在Web浏览器中打开这个文件的话,那么它就会显示了。
2577 0
|
3月前
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
750 0
|
7月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
318 0
|
7月前
|
Java 测试技术 微服务
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
本课主要讲解Spring Boot项目中的属性配置方法。在实际开发中,测试与生产环境的配置往往不同,因此不应将配置信息硬编码在代码中,而应使用配置文件管理,如`application.yml`。例如,在微服务架构下,可通过配置文件设置调用其他服务的地址(如订单服务端口8002),并利用`@Value`注解在代码中读取这些配置值。这种方式使项目更灵活,便于后续修改和维护。
101 0
|
7月前
|
SQL Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录—— application.yml 中对日志的配置
在 Spring Boot 项目中,`application.yml` 文件用于配置日志。通过 `logging.config` 指定日志配置文件(如 `logback.xml`),实现日志详细设置。`logging.level` 可定义包的日志输出级别,例如将 `com.itcodai.course03.dao` 包设为 `trace` 级别,便于开发时查看 SQL 操作。日志级别从高到低为 ERROR、WARN、INFO、DEBUG,生产环境建议调整为较高级别以减少日志量。本课程采用 yml 格式,因其层次清晰,但需注意格式要求。
638 0