> 文章列表 > SpringBoot集成Thymeleaf模板引擎的html、css和js存放位置

SpringBoot集成Thymeleaf模板引擎的html、css和js存放位置

SpringBoot集成Thymeleaf模板引擎的html、css和js存放位置

前言:前端时间支援公司其他部门的医保大屏项目,和前端同事前后端分离手写,部署为了方便就把前端VUE打包成Dist文件放入后端的Thymeleaf模板引擎中,特此记录下集成姿势。

1. SpringBoot集成Thymeleaf模板引擎的html页面

在pom.xml文件中增加thymeleaf的starter引用

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

2、在application.yml配置文件中增加如下配置

spring:thymeleaf:prefix: classpath:/templatessuffix: .htmlcache: false
  • prefix

  • prefix意为前缀

  • suffix

  • suffix意为后缀

如我的页面为hello-world.html,它所在的目录结构就应该为resource–> templates --> hello-world.html在controller中,return的值则为 /hello-world ,系统会自动给加上.html的后缀

3、controller中访问hello-world.html页面

@Controller
@RequestMapping("/")
public class HelloWorldController {@RequestMapping("hello-world")public String index() {return "/hello-world";}
}

4、页面中引用本地js、css文件的路径配置

我的页面中本来都是直接使用的element-ui和vue直接提供的在线js,但是因为页面嵌套会有跨域的问题,所以页面中的js、css都要改为使用本地文件。

在resource目录下,创建static目录,在static目录下分别创建js目录和css目录来存放js文件和css文件。

在springboot入口的Application文件中增加WebMvc配置,首先继承WebMvcConfigurationSupport类,然后重写addResourceHandlers方法,在里面增加对/css路径和/js路径的映射。

  public class ApplicationBootStrap extends WebMvcConfigurationSupport {public static void main(String[] args) {SpringApplication.run(ApplicationBootStrap.class, args);}@Overrideprotected void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/css/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/css/");registry.addResourceHandler("/js/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/js/");super.addResourceHandlers(registry);}}

5、前端页面引用配置

  1. html标签 要增加 xmlns:th="http://www.thymeleaf.org" 引用

  2. <header>标签中增加 <base th:href="@{/}"> 配置

  3. css引入增加 th:href配置路径,js引入增加th:src路径配置。这里要注意link要有 rel="stylesheet" ,script要有type="text/javascript"的格式说明,这是规范。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><base th:href="@{/}"><meta charset="UTF-8"><!-- import CSS --><link rel="stylesheet" href="../../static/css/index.css" th:href="@{/css/index.css}"/>
</head>
<body>
<div id="app"></div>
</body>
<!-- import Vue before Element -->
<script src="../../static/js/vue-2.6.12.js" th:src="@{/js/vue-2.6.12.js}" type="text/javascript"></script>
<!-- import JavaScript -->
<script src="../../static/js/index.js" th:src="@{/js/index.js}" type="text/javascript"></script>
<script src="../../static/js/jquery1.7.2.min.js" th:src="@{/js/jquery1.7.2.min.js}" type="text/javascript"></script>
<script>let vm = new Vue({el: '#app',.....业务代码省略....})
</script>
</html>