Spring boot 打包jar后静态资源的访问
背景: Spring boot 打包成jar包后访问不到静态资源
首先spring boot有默认的文件夹设置,且能够自己识别静态资源,下面是spring boot默认的静态文件夹指定:
org.springframework.boot.autoconfigure.web.ResourceProperties
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {"classpath:/META-INF/resources/",
"classpath:/resources/","classpath:/static/", "classpath:/public/" };
pom.xml 使用 spring-boot-maven-plugin 默认的打包方式,讲道理”classpath:/static/”已经可以了,可就是不行。
具体心路历程就不写了,直接说我的环境下解决的方法
修改WebMvcConfigurer配置,覆写addResourceHandlers
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
...
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 需要告知系统,这是要被当成静态文件的!
// 第一个方法设置访问路径的匹配方式(该方式有一大缺点,controller的路径不得为*.*的格式),第二个方法设置资源路径(file可以用以进行扩展,例如上传的图片等)
registry.addResourceHandler("**/*.*").addResourceLocations("classpath:/resources/", "classpath:/static/",
"classpath:/public/", "file:./static-extend/");
}
}
拦截器要注意将静态资源排除掉,以上这种方式,既可以jar包,也可以IDE内运行,相反如果只有”classpath:/static/”的话IDE又跪了。
POM.XML 使用默认的即可(即static、templates文件夹默认放在BOOT-INF/class下就好)
${project.artifactId}
org.springframework.boot
spring-boot-maven-plugin
顺便说下thymeleaf踩坑的地方
一定要在后面加上一个反斜!一个反斜!!一个反斜!!
然后代码里面 return 的时候前面一定要去掉反斜!去掉反斜!!去掉反斜!!!
spring:
thymeleaf:
prefix: classpath:/templates/
@RequestMapping("/demo")
@Controller
public class DemoController {
@RequestMapping("/index")
@ResponseBody
public Object index() {
return new ResultModel();
}
@RequestMapping("/error")
public ModelAndView error(){
ModelAndView modelAndView = new ModelAndView("collect/error");
modelAndView.addObject("error", "参数错误");
return modelAndView;
}
@RequestMapping("/finish")
public String finish() {
return "collect/finish";
}
}
完成以上配置后就可以jar、IDE完美运行了,并且在jar包的路径下static-extend文件夹下可以方便的存放静态资源,安全性就要看大家的需求了,它最终是靠spring boot进行操作的。
参考文献