SpringBoot跳转页面详解之菜鸡踩坑日志
在初次使用springboot搭建一个web项目时,访问templates文件夹下的静态页面报404错误,开始以为网络问题,使得在线下载的springboot项目有问题,最后多方查阅发现错误,特此记录一下
1、初始化一个springboot进行测试使用controller访问templates文件夹下的页面,我们会发现会报404错误,原因是我们需要配置ViewResolver视图解析器前缀与后缀,这个时候默认访问是访问失败的。
2、如果不配置ViewResolver视图解析器前缀与后缀也想访问templates文件夹下的静态页面,这个时候我们需要引入springboot集成thymeleaf的依赖,因为thymeleaf的配置文件默认配置前缀与后缀。
1 <!-- springboot集成thymeleaf --> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-starter-thymeleaf</artifactId> 5 </dependency>
1 @ConfigurationProperties(prefix = "spring.thymeleaf") 2 public class ThymeleafProperties { 3 4 private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; 5 6 public static final String DEFAULT_PREFIX = "classpath:/templates/"; 7 8 public static final String DEFAULT_SUFFIX = ".html"; 9 10 /** 11 * Whether to check that the template exists before rendering it. 12 */ 13 private boolean checkTemplate = true; 14 15 /** 16 * Whether to check that the templates location exists. 17 */ 18 private boolean checkTemplateLocation = true; 19 20 /** 21 * Prefix that gets prepended to view names when building a URL. 22 */ 23 private String prefix = DEFAULT_PREFIX; 24 25 /** 26 * Suffix that gets appended to view names when building a URL. 27 */ 28 private String suffix = DEFAULT_SUFFIX; 29 30 /** 31 * Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum. 32 */ 33 private String mode = "HTML"; 34 35 /** 36 * Template files encoding. 37 */ 38 private Charset encoding = DEFAULT_ENCODING; 39 40 /** 41 * Whether to enable template caching. 42 */ 43 private boolean cache = true;
3、如果将静态页面放入static文件夹下,想通过controller访问,那么返回值处不能只写页面名,还需要将页面的后缀带上,例如index.html。
4、在没有过滤器、拦截器等一系列操作下,我们发现我们的页面的css、js无法访问,但是我们确实放在static文件夹下,该文件夹下的文件在外部是可以访问的,如果你将外部的文件夹直接复制放在static文件夹下,可能出现静态资源无法访问的问题,原因是外部文件夹在项目中无法被识别,我们可以右键该项目文件夹Rebulid一下,让该文件下的所有文件及文件夹可以被项目识别。