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

Maven SpringBoot Eclipse项目中AngularJS路由无法找到.html模板

解决AngularJS + Spring Boot路由模板404问题

我来帮你分析下这个问题,核心原因是Spring Boot的资源访问规则和AngularJS路由的模板路径不匹配。Spring Boot默认把src/main/resources/templates目录作为模板引擎(比如Thymeleaf)的渲染目录,不是前端可以直接访问的静态资源目录,所以AngularJS请求这里的HTML文件会返回404。下面是具体的解决步骤:

1. 调整模板文件的存放位置

把你的first.html、second.html、main.html从src/main/resources/templates目录,移动到src/main/resources/static/templates目录下(如果templates目录不存在就新建一个)。这样这些HTML文件就变成了静态资源,前端可以直接访问。

调整后的项目目录结构应该是:

-src/main/java
|-com.package
|---Application.java
|---ViewController.java
-src/main/resources
|---static
-----app
------app.module.js
-----templates
------first.html
------main.html
------second.html
-----angular-route.min.js
-----angular.min.js
-----angular.min.js.map
-----style.css
|---templates
-----index.html

2. 修改AngularJS路由的templateUrl路径

更新app.module.js里的路由配置,把模板路径改成对应静态资源的路径:

var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', { templateUrl: "templates/main.html" }) // 这里也改成templateUrl,用正确路径
.when("/first", { templateUrl: "templates/first.html" })
.when('/second', { templateUrl: 'templates/second.html' })
.otherwise({redirectTo: '/'});
});

3. 验证静态资源可访问性

启动Spring Boot项目后,直接在浏览器地址栏访问http://localhost:8080/templates/first.html,如果能看到<p>first</p>的内容,说明静态资源路径配置正确。这时候再测试AngularJS的路由导航,应该就能正常加载模板了。

额外注意点

  • 确保index.html中引入AngularJS脚本的路径正确,比如:
    <script src="angular.min.js"></script>
    <script src="angular-route.min.js"></script>
    <script src="app/app.module.js"></script>
    
  • 你的ViewController配置没问题,@RequestMapping("/")返回index会让Spring Boot从templates目录加载index.html,这个是正确的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:37:07