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
相关产品推荐
相关产品推荐

