Spring Boot添加HTML和JavaScript

zaq*_*otr 19 javascript spring-mvc spring-boot

我正在尝试使用一些HTML5和JavaScript运行Spring启动应用程序,我遇到了问题.

我有这样的项目结构:

在此输入图像描述

我的Spring MVC控制器正在调用文件offer.html,并且工作正常.

我的offer.html文件如下所示:

<!DOCTYPE html>
<html lang="en" ng-app="coByTu">
<head>
    <title>Page</title>
    <script type="text/javascript" src="../js/lib/angular.js" />
    <script type="text/javascript" src="../js/src/offer.js" />
</head>
<body>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

当我输入我的应用程序URL http:// localhost:8080/offerView时

服务器的响应是:

在此输入图像描述

我不知道为什么我的应用程序没有看到这个脚本文件,任何人都知道我做错了什么?

Eri*_*ric 39

基本上所有需要静态提供的内容(例如javascript文件)都应放在静态文件夹下. https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot

我把一个快速的工作示例放在一起,以显示它是如何完成的:https: //github.com/ericbv/staticContentWithSpringBoot

文件结构: 在此输入图像描述

HTML文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Page</title>
    <script type="text/javascript" th:src="@{/js/lib/angular.js}" />
    <script type="text/javascript" th:src="@{/js/src/offer.js}" />
</head>
<body>
Run Code Online (Sandbox Code Playgroud)

使用th:src将确保链接具有上下文感知功能

编辑:添加th:src以使引用上下文可识别

  • 这是一个糟糕的做法.这里没有使用thymeleaf会在有contextPath时破坏页面(即在独立应用程序服务器内部使用时) (2认同)
  • 如果您的应用程序具有上下文路径,它将无法工作.通常,在从独立应用程序服务器运行应用程序时,或者在application.properties中添加应用程序时,您将拥有上下文路径.如果要模拟上下文路径(查看何时使用src中断),请将以下行添加到applicaiton.properties文件中:"server.contextPath =/context"这将导致页面url为localhost:8080/context/offerView现在在这种情况下,它只适用于src的thymeleaf变体,因为这将考虑上下文. (2认同)

小智 7

仅供任何人找到具有相同问题的页面。我解决“脚本未执行”问题的方法非常简单。

简单地替换:

<script type="text/javascript" src="js/src/Test.js" />
Run Code Online (Sandbox Code Playgroud)

<script type="text/javascript" src="js/src/Test.js" ></script>
Run Code Online (Sandbox Code Playgroud)

(测试位于“static/js/src”中)希望这对除了我之外的任何人都有帮助:)

干杯