【问题标题】:Spring boot static resources and controllers endpoint mixedSpring Boot 静态资源和控制器端点混合
【发布时间】:2020-06-03 09:56:17
【问题描述】:

我有一个端点 'localhost:8080/users' 和一个控制器,它应该将任何匹配 '/users/**' 模式的请求重定向到 'localhost:8080/users' 并通过返回 index.html 文件显示登录页面这是角度应用的入口点。我在目录“..resources/static/users”中还有一个静态资源,其中包含构建的角度应用程序。 index.html 文件如下所示:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <base href="/users/" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
  <body>
    <app-root></app-root>
  <script src="runtime-es2015.js" type="module"></script><script src="runtime-es5.js" nomodule defer></script><script src="polyfills-es5.js" nomodule defer></script><script src="polyfills-es2015.js" type="module"></script><script src="styles-es2015.js" type="module"></script><script src="styles-es5.js" nomodule defer></script><script src="vendor-es2015.js" type="module"></script><script src="vendor-es5.js" nomodule defer></script><script src="main-es2015.js" type="module"></script><script src="main-es5.js" nomodule defer></script></body>
</html>

问题是对静态 js 文件的任何请求都与我的控制器端点模式匹配并返回 index.html 文件。如何解决这样的问题?

【问题讨论】:

    标签: spring spring-boot spring-mvc model-view-controller


    【解决方案1】:

    使用ResourceResolver 解析静态资源。

    来自Static Resources section in Spring Framework Reference

    给定一个以/resources开头的请求,相对路径是 用于查找和服务相对于/public 下的静态资源 Web 应用程序根目录或/static 下的类路径。

    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/resources/**")
                .addResourceLocations("/public", "classpath:/static/")
                .setCachePeriod(31556926);
        }
    }
    

    还有,

    WebJars 也通过WebJarsResourceResolver 得到支持,该WebJarsResourceResolverorg.webjars:webjars-locator-core 时自动注册 库存在于类路径中。

    【讨论】:

      猜你喜欢
      • 2016-10-01
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多