【问题标题】:No mapping for static-resources Spring Boot没有静态资源 Spring Boot 的映射
【发布时间】:2020-07-21 10:49:04
【问题描述】:

在我的 Spring-Boot 应用程序中,js 和 css 文件不起作用,它说 404 not found。

我的 html 页面包括以下内容:

  <head>  
     <link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet">
     <link href="/static/css/style.css" rel="stylesheet">
     <script src="/webjars/jquery/jquery.min.js"></script>
     <script src="/webjars/sockjs-client/sockjs.min.js"></script>
     <script src="/webjars/stomp-websocket/stomp.min.js"></script>
     <script src="/static/js/operations.js"></script>
 </head>

我这样配置资源:

 @Configuration
 @EnableWebMvc
 public class MvcConfig implements WebMvcConfigurer {
     @Override
     public void addResourceHandlers(ResourceHandlerRegistry registry) {
         registry
               .addResourceHandler("/resources/**")
               .addResourceLocations("/resources/");
        }
  }

但在我收到的日志中:

  o.s.web.servlet.PageNotFound             : No mapping for GET /favicon.ico
  o.s.web.servlet.PageNotFound             : No mapping for GET /favicon.ico
  o.s.web.servlet.PageNotFound             : No mapping for GET /webjars/jquery/jquery.min.js
  o.s.web.servlet.PageNotFound             : No mapping for GET /static/css/style.css
  o.s.web.servlet.PageNotFound             : No mapping for GET /static/js/operations.js
  o.s.web.servlet.PageNotFound             : No mapping for GET /favicon.ico

这是静态源的位置:

我做错了什么?

【问题讨论】:

  • 您是否配置了安全性以允许这些请求?
  • 没有。未配置安全性。
  • 而 contextPath 是?
  • 我怎样才能找到 contextPath?
  • applicationContext 是。 "/"

标签: java html spring spring-boot staticresource


【解决方案1】:

默认情况下,此处理程序从类路径上的任何/static, /public, /resources, and /META-INF/resources 目录中提供静态内容。由于src/main/resources 通常默认位于类路径中,因此我们可以将这些目录中的任何一个放在那里。

这意味着您的链接应如下所示:

<link href="/css/style.css" rel="stylesheet">

而不是

<link href="/static/css/style.css" rel="stylesheet">

【讨论】:

  • 可以去掉 MvcConfig 类试试吗?
【解决方案2】:

我能够使用以下路径解决项目中的问题

href="${pageContext.request.contextPath}/resources/static/..."

所以尝试使用下面的路径

href="${pageContext.request.contextPath}/resources/static/css/style.css"

可能有更好的解决方法,但在此之前这是一个快速修复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 2016-10-01
    • 2016-12-24
    • 2016-07-01
    • 1970-01-01
    相关资源
    最近更新 更多