在编写个人博客框架时,启动项目后,html文件中静态资源访问不到,出错信息如下:
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "css"
一开始是按照网上的css和js引入方式:
<link rel="stylesheet" th:href="@{/css/me.css}">
引入图片也是这种方式,一直显示类型转换错误。。。。人都傻了(感觉可能是路径写错了),后面去查了博客,自己摸索了一下解决了这个问题,但是没有去深究,求大佬们给个传送门深入了解静态资源配置和拦截问题。
解决办法:
1.编写了拦截器放行资源
2.重新编写引入方式
第一步:查阅了一些博客之后,普遍说的是springboot2.0之后会拦截静态资源,针对拦截,编写拦截器放行静态资源
目录结构:
尽量不要去继承WebMvcConfigurerAdapter,这个已经被WebMvcConfigurer取代,已经弃用了
@EnableWebMvc
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:static/");
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
第二步:引入js和css文件
<link rel="stylesheet" th:href="@{/static/css/me.css}">
<script th:src="@{/static/js/jquery.min.js}"></script>
一般出错的话,可能是没有加"/",也可能是没有加static(虽然能够引用了,但是不清楚为什么要加static,为什么@{/css/me.css}不可以直接访问,求解答)
这是因为在拦截器中定义了放行/static/**的资源,因此当需要引用静态资源时标注一下。
水平有限,错误请指正!一起学习,一起进步,感谢!