spring boot访问静态资源时报这个错,目前发现两个原因
主要是视图解析器问题
1、查看控制器路径是否和返回字符串一样,这两个地方是不能一样的
@RequestMapping("/tohello")//控制器路径
public String hello(){
return "hello";//静态资源路径
}
2、是不是在.properties或.yml配置文件里修改了静态资源默认位置,且没有自定义视图解析器?或者相反
spring.web.resources.static-locations=classpath:/myPages/
或者
spring:
web:
resources:
static-locations: /myPages/
根本原因:
spring boot修改默认静态资源路径后,自动拼接返回字符串后缀会失效,这样返回的就不是/hello.html,而是/hello
解决办法:
1、(推荐).properties或.yml配置文件里设置后缀;
spring.mvc.view.suffix=.html
2、创建一个配置类,自定义视图解析器,自己设置视图解析器前缀和后缀;
3、或者就别修改默认的静态资源位置了吧
@Configuration
public class MyConfiguration implements WebMvcConfigurer {
@Bean
public ViewResolver myViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/");//前缀
resolver.setSuffix(".html");//后缀
return resolver;
}
}