最近用spring boot 搭建个项目,访问页面时静态资源加载不出来,百度了一番找到一个解决方案。
解决方案如下
1、controller代码
@Controller
public class IndexController {
@RequestMapping("/")
public String index() {
return "index";
}
}
2、html页面代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link th:href="@{/static/css/index.css}" rel="stylesheet">
</head>
<body>
<h1>Hello World !!!</h1>
</body>
</html>
3、增加一个WebMvcConfigurer
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
4、依赖如下
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
5、结果如下