【问题标题】:How to load a js source in Spring MVC如何在 Spring MVC 中加载 js 源
【发布时间】:2014-11-11 16:13:47
【问题描述】:

我正在尝试在 Spring MVC 服务器中的 html 页面中加载 js 脚本源。

Spring MVC 中的文件夹

html页面位于:src/main/webapp/WEB-INF/view/mapa.html

js 位于视图子文件夹中: src/main/webapp/WEB-INF/view/js/infobox.js

这是我的html页面ma​​pa.html

    <!DOCTYPE html>
    <html>
      <head>
       <style>
      #map_canvas {
        width: 500px;
        height: 400px;
      }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <!-- Caixa de informação -->
    <script src="js/infobox.js"></script>
    <!-- Agrupamento dos marcadores -->
    <script src="js/markerclusterer.js"></script>
    </head>
   <body>
   //code...
   </body>
   </html>   `

我正在尝试使用 mapa.html 加载 infobox.js,但它没有加载。 这个源路由正确吗??

【问题讨论】:

    标签: javascript spring


    【解决方案1】:

    您的相对路径很好,但您可能缺少 Spring MVC 中的配置,这将有助于有效地提供静态资源。在您的情况下,spring mvc 配置应该包含类似

    <resources mapping="/js/**" location="/WEB-INF/views/js/" />
    

    更好的方法是在 webapp 的根目录中创建一个资源文件夹,并在 spring mvc 配置中添加一个类似的条目

    <resources mapping="/resources/**" location="/resources/" />
    

    并将所有静态资源放在资源子文件夹中并通过

    <script type="text/javascript" src="/resources/js/..."></script>
    

    css 类似

    【讨论】:

    • 知道使用@Bean 方法添加这个&lt;resources mapping="/resources/**" location="/resources/" /&gt; 吗?我在 Spring 应用程序中使用 @EnableAutoConfiguration
    • 好的,所以你使用的是spring-boot,据我所知,资源应该是已经映射的默认位置之一。至少易于测试,只需将您的 /js 文件夹移动到 webaapp 根目录下的 /resources 文件夹,然后尝试通过 /resources/js.. 从页面访问。应该工作
    【解决方案2】:

    试试

    <script src="./view/js/infobox.js"></script>
    

     <script src="./view/js/markerclusterer.js"></script>
    

    【讨论】:

      猜你喜欢
      • 2016-11-18
      • 2015-05-25
      • 2017-03-08
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 2013-04-07
      • 1970-01-01
      • 2019-01-30
      相关资源
      最近更新 更多