引入资源
Spring Boot的项目,在静态资源文件夹下有index.html文件的,默认访问的首页会指向静态资源文件夹下的index.html。而想要得到模板引擎渲染的页面就只有放在templates下的HTML页面才能使用模板引擎对其进行渲染。
想要修改默认访问的首页(使用localhost:8080
/localhost:8080/index.html
),可以有以下几种方式:
- 使用Controller发请求
@RequestMapping({
"/", "/index", "/index.html"})
public String index() {
return "index";
}
- 自己写的配置类中添加视图解析器
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 浏览器发送/caesar请求到success页面
registry.addViewController("/caesar").setViewName("success");
registry.addViewController("/").setViewName("index");
registry.addViewController("/index").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
}
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
};
}
使用thymeleaf引入资源
- 引入webjars的资源
<!-- 1. 现在pom文件中引入所需的webjars的依赖-->
<!--bootstrap-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.3.1</version>
</dependency>
<!-- 2. 引入thymeleaf提示代码 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!-- 3. 使用【th:attr】修改引入资源的路径 -->
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.3.1/css/bootstrap.css}" rel="stylesheet">
- 引入自定义资源
<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
<img class=