Springboot访问templates页面下文件的几种方法
- springboot整合了springmvc的拦截功能。拦截了所有的请求。默认放行的资源是:resources/static/ 目录下所有静态资源。(不走controller控制器就能直接访问到资源)
- html页面如果放在resources/templates目录下,则需要走controller控制器,controller放行,允许该资源访问,该资源才能被访问到。否则就会报404错误(它不可以直接被访问)
很重要
无论是方法一还是方法二必须添加 thymeleaf 依赖如下,否则404:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
方法一:
引入控制器类去捕获url,然后映射到templates文件夹下的index.html
@Controller
public class UserController {
@RequestMapping({"/", "/index.html"})
public String index(){
return "index";
}
}
方法二:
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index").setViewName("index");
registry.addViewController("/login").setViewName("login");
}
}