You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Maven项目中HTML引入JavaScript文件的问题求助

Maven Web项目静态资源访问问题解决

一、调整为标准项目结构

先把项目结构改成Maven Web项目的规范结构,避免资源路径混淆:

Project
  src
    main
      java
        Server.java
      webapp
        html
          index.html
        js
          index.js
        css
          style.css
      resources  <!-- 此目录放配置文件,不要放网页静态资源 -->
  pom.xml

注:src/main/resources是Maven用来存放类路径配置文件的目录,网页静态资源直接放在webapp下的子目录更清晰。

二、修复服务器端静态资源映射逻辑

你遇到的Unexpected token '<'错误,本质是服务器没有正确处理/js/index.js的请求,返回的是HTML内容(比如404页面或index.html),浏览器把HTML当成JS解析才会报错。

如果是自定义HttpServer

需要在Server.java中添加静态资源的处理逻辑,示例代码:

public void handle(HttpExchange exchange) throws IOException {
    String requestPath = exchange.getRequestURI().getPath();
    // 把请求路径映射到webapp目录下的文件
    String filePath = "src/main/webapp" + requestPath;
    File targetFile = new File(filePath);

    if (targetFile.exists() && !targetFile.isDirectory()) {
        // 返回静态资源文件
        exchange.sendResponseHeaders(200, targetFile.length());
        try (OutputStream out = exchange.getResponseBody()) {
            Files.copy(targetFile.toPath(), out);
        }
    } else {
        // 返回404页面
        String errorHtml = "<html><body>404 资源不存在</body></html>";
        exchange.sendResponseHeaders(404, errorHtml.getBytes().length);
        try (OutputStream out = exchange.getResponseBody()) {
            out.write(errorHtml.getBytes());
        }
    }
}

如果是Spring Boot项目

确保静态资源配置正确,默认情况下Spring Boot会自动识别webapp下的静态资源,若需自定义可在application.properties中添加:

spring.mvc.static-path-pattern=/**
spring.web.resources.static-locations=classpath:/webapp/

三、修正HTML中的资源引用路径

推荐使用绝对路径引入JS/CSS,避免页面层级变化导致路径失效,修改index.html的代码:

<head>
  <script src="/js/index.js"></script>
  <!-- 后续引入CSS可参考此格式 -->
  <link rel="stylesheet" href="/css/style.css">
</head>

四、打包配置验证

如果是自定义打包逻辑,需要在pom.xml中添加资源打包规则,确保静态资源被正确打入jar包:

<build>
  <resources>
    <resource>
      <directory>src/main/webapp</directory>
      <targetPath>META-INF/resources</targetPath>
    </resource>
  </resources>
</build>

执行mvn package后,静态资源会被打包到jar的META-INF/resources目录下,保证运行时可访问。

额外修正:JS代码的小问题

你提供的JS代码中,事件绑定存在错误:

// 错误写法:会立即执行validateRegistration,而非提交时触发
document.getElementById("register").addEventListener("submit", validateRegistration());
// 正确写法:传递函数引用
document.getElementById("register").addEventListener("submit", validateRegistration);

内容的提问来源于stack exchange,提问作者Tomaspolar50

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 04:11:05