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帮助我们进行扩展配置。

相关文章
|
27天前
|
XML Java 应用服务中间件
Spring Boot 两种部署到服务器的方式
本文介绍了Spring Boot项目的两种部署方式:jar包和war包。Jar包方式使用内置Tomcat,只需配置JDK 1.8及以上环境,通过`nohup java -jar`命令后台运行,并开放服务器端口即可访问。War包则需将项目打包后放入外部Tomcat的webapps目录,修改启动类继承`SpringBootServletInitializer`并调整pom.xml中的打包类型为war,最后启动Tomcat访问应用。两者各有优劣,jar包更简单便捷,而war包适合传统部署场景。需要注意的是,war包部署时,内置Tomcat的端口配置不会生效。
201 17
Spring Boot 两种部署到服务器的方式
|
1月前
|
移动开发 前端开发 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 等属性,可以抽取和复用公共页面片段,并支持参数传递。
107 12
|
3月前
|
存储 运维 安全
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
通过以上措施,可以保证Spring Boot项目的配置管理在专业水准上,并且易于维护和管理,符合搜索引擎收录标准。
79 2
|
4月前
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
138 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
|
4月前
|
缓存 NoSQL Java
Springboot自定义注解+aop实现redis自动清除缓存功能
通过上述步骤,我们不仅实现了一个高度灵活的缓存管理机制,还保证了代码的整洁与可维护性。自定义注解与AOP的结合,让缓存清除逻辑与业务逻辑分离,便于未来的扩展和修改。这种设计模式非常适合需要频繁更新缓存的应用场景,大大提高了开发效率和系统的响应速度。
117 2
|
6月前
|
Java Spring
Spring boot +Thymeleaf 本地图片加载失败(图片路径)的问题及解决方法
这篇文章详细讲解了在Spring Boot应用程序中本地图片无法加载的问题原因,并提供了两个示例来说明如何通过使用正确的相对路径或Thymeleaf语法来解决图片路径问题。
|
6月前
|
消息中间件 Java Kafka
Spring Boot与模板引擎:整合Thymeleaf和FreeMarker,打造现代化Web应用
【8月更文挑战第29天】这段内容介绍了在分布式系统中起到异步通信与解耦作用的消息队列,并详细探讨了三种流行的消息队列产品:RabbitMQ、RocketMQ 和 Kafka。RabbitMQ 是一个基于 AMQP 协议的开源消息队列系统,支持多种消息模型,具有高可靠性及稳定性;RocketMQ 则是由阿里巴巴开源的高性能分布式消息队列,支持事务消息等多种特性;而 Kafka 是 LinkedIn 开源的分布式流处理平台,以其高吞吐量和良好的可扩展性著称。文中还提供了使用这三种消息队列产品的示例代码。
46 0
|
7月前
|
Java 数据处理 Spring
Spring Boot中的模板引擎选择与配置
Spring Boot中的模板引擎选择与配置
|
8月前
|
前端开发 Java Spring
Spring Boot中使用Thymeleaf进行页面渲染
Spring Boot中使用Thymeleaf进行页面渲染
|
8月前
|
Java 数据处理 Spring
Spring Boot中的模板引擎选择与配置
Spring Boot中的模板引擎选择与配置