这篇文章主要介绍了springboot访问静态资源遇到的坑及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
访问静态资源遇到的坑及解决
它从这个结构开始,产生了一个红色的页面,访问的页面看起来是这样的。
终于找出问题了,虽然每次路径都不正确。最后,你可以通过观察各种方法来了解它:
添加:
package com.example.demo.config;import org.springframework.stereotype.Component;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Componentpublic class WebConfig implements WebMvcConfigurer {/* * 添加静态资源文件,外部可以直接访问地址 * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); }}
所以你可以问:
直接访问静态资源的问题
目前一般是前后端分离,SpringBoot主要提供接口服务。但是有时候一些小项目只是希望一个jar的前端和后端完成,所以把页面等一些静态资源放到SpringBoot里。这里记录一下静态资源访问方法和引入shiro后的修改。
SpringBoot 默认静态资源访问配置
SpringBoot的默认配置可以直接URL访问下面路径中的静态资源
classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public/
优先顺序按上述顺序。
假设端口设置为8080,URL访问http://localhost:8080/index . html,请注意URL路径中没有添加static/
测试结果表明,META-INF-gt;资源不足的Index.html
SpringBoot中默认配置的静态资源路径的值是由变量spring . resources . static-locations控制的,一般我们不用修改。
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ # Locations of static resources.
引入shiro 或 security后的拦截过滤
首先,假设shiro或security拦截SpringBoot的所有访问路径(/* *)。在这种情况下,我想把我的页面、js、css、图片等静态资源放在static下,这样shiro或者security就不会拦截这些资源了。我该如何配置它们?
假设您的静态资源目录如下:
起初,我是这样想的:
filterRuleMap.put("/static/**", "anon");
也就是说,静态路径下的所有静态资源都被释放,但是找到了访问404。
实际上,src/main/resources/static是存储静态资源的目录,而不是url访问目录。您应该为静态目录中的资源配置过滤规则。
可以这样配置。以下是shiro的静态资源过滤配置,和security的一样,主要关注哪些url路径需要过滤。
// 图片js文件等过滤配置filterRuleMap.put("/css/**", "anon");filterRuleMap.put("/js/**", "anon");filterRuleMap.put("/img/**", "anon");filterRuleMap.put("/pages/**", "anon");// 首页过滤配置filterRuleMap.put("/index.html", "anon");filterRuleMap.put("/", "anon");
通过这种方式,您可以访问静态资源并访问index.html。
如果发现要配置很多文件,可以把所有的原始文件放在一个统一的目录myfiles下,过滤这个目录,如下图所示:
filterRuleMap.put("/myfiles/**", "anon");// 首页过滤配置filterRuleMap.put("/index.html", "anon");filterRuleMap.put("/", "anon");
但是当你访问主页的时候,你需要在URL路径中添加这个myfiles,localhost:8080/my files/index . html。
一个愚蠢的解决方案是添加一个额外的index.html页面,直接跳转到/myfiles/index.html页面。
lt;scriptgt; window.location.href = 'pages/index.html';lt;/scriptgt;
以上个人经验,希望能给你一个参考
精彩评论