这次项目突发奇想想用一次springboot,但是入坑才发现坑好多啊。
项目说明:springboot版本是2.2.2,jdk是1.8
springboot官方推荐使用thymeleaf模板引擎,把静态资源放到resources下面的static中,然后页面放到templement中,但这次因为时间比较紧,所以我想把以前项目里面的webapp直接搬过来,里面的jsp直接使用,结果jsp能访问到,但里面的图片,css,js全都报404错误。
目录结构:
直接在与java同级创建一个webapp目录, 然后把以前旧spring MVC项目中的webapp直接复制了过来。
结果访问里面的jsp可以正常访问到,但静态资源全都找不到了。
单独访问css都是都跳转到报错页面
道理我知道点,应该是springboot默认拦截所有uri用作各种处理,然后就把静态资源也拦了,想不拦就得配置放行。
然后百度了一堆方法不过可能是springboot版本不一样或者是jdk版本不一样,反正就是实现不了,prop文件配置也不生效,最后好不容易找到一个我这个版本可以使用的方法:
springboot默认扫描的静态资源的路径是这些
classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources
我们的目标就是就是把webapp中的内容编译到最后一种classpath:/META-INF/resources中,然后放行这个路径即可
解决方法:
1.在pom.xml中的build->resources中增加这个,作用是吧webapp编译到 META-INF/resources 中
<resource>
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>**/**</include>
</includes>
</resource>
这种重新编译后可以看到webapp已经被编译进去了
2.增加一个配置类
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class staticConfig implements WebMvcConfigurer {
//这个写不写没啥用
/* @Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.excludePathPatterns("/META-INF/resources*");
}*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/");
}
}
这样访问,我的css,js终于出来了!!!
如果还有问题,需要检查是否拦截器中return成false了,如果返回结果不是404,而是500啥的,需要检查是否是设置了字符集编码转换造成的,我找不到的一个原因就是字符集转换造成的。
ps:虽说springboot放行了静态资源拦截,我加了登录拦截器后静态资源又被拦截器拦截了。
所以又得指定放行相关文件,增加excludePathPatters就行
package com.bomc.enterprise.config;
import com.bomc.enterprise.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class WebConfig implements WebMvcConfigurer {
//不注册这个在过滤器中 service将报空
@Bean
public LoginInterceptor loginInterceptor(){
return new LoginInterceptor();
}
//添加拦截器方法
@Override
public void addInterceptors(InterceptorRegistry registry) {
//添加拦截路径
String[] addPathPatters={
"/**"
};
//添加不拦截路径
String[] excludePathPatters={
"/", "/login/login", "/login/loginPage","/login/register",
"/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg",
"/**/*.jpeg", "/**/*.gif", "/**/fonts/*", "/**/*.svg",
"/**/*.ttf","/**/*.woff","/**/*.eot","/**/*.otf","/**/*.woff2"
};
//注册登录拦截器
registry.addInterceptor(loginInterceptor()).addPathPatterns(addPathPatters).excludePathPatterns(excludePathPatters);
//如果多条拦截器则增加多条
}
//添加放行静态资源
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/");
}
}