如何在JSP页面中用AngularJS变量动态修改script标签路径?
解决根据生产环境动态切换Script路径的问题
看起来你遇到的核心问题是直接在静态script标签的src属性中使用Angular插值语法不生效,而且需要结合JSP的EL表达式来动态拼接路径。我们一步步来解决这个问题:
首先,纠正production状态的获取逻辑
你之前用split的方式提取参数不够可靠(比如参数不在URL末尾时会出错),推荐使用原生的URLSearchParams来安全获取布尔值:
const urlParams = new URLSearchParams(location.search); // 确保拿到的是严格的布尔值 const isProduction = urlParams.get('production') === 'true';
为什么你的插值写法失效?
Angular的{{}}插值语法只在Angular组件模板中生效,而你当前是在JSP页面的静态<script>标签里,浏览器不会解析这种语法。另外,JSP的EL表达式(${param.userId})是在服务器端渲染的,和前端的Angular插值不能直接混写在静态属性里。
最优解决方案:动态创建Script标签
我们可以用JavaScript动态生成script标签,这样既能结合JSP渲染的变量,又能根据生产环境切换路径:
<script> // 1. 获取生产环境状态 const urlParams = new URLSearchParams(location.search); const isProduction = urlParams.get('production') === 'true'; // 2. 从JSP渲染结果中拿到用户ID和文件名(服务器端先替换EL表达式) const userId = '${param.userId}'; const fileName = '${param.fileName}'; // 3. 根据环境拼接路径 const basePath = isProduction ? '../rest/project1/getSource/' : 'rest/project1/getSource/'; const scriptSrc = `${basePath}${userId}/${fileName}`; // 4. 动态创建并添加script标签到页面 const scriptElement = document.createElement('script'); scriptElement.src = scriptSrc; // 可选:监听脚本加载完成事件 scriptElement.onload = () => { console.log('外部脚本加载完成'); }; document.body.appendChild(scriptElement); </script>
如果是在Angular组件模板中(非JSP场景)
如果你的页面是Angular组件的模板文件(比如.html),可以用Angular的属性绑定语法来实现,不需要手动创建标签:
- 在组件类中准备好变量:
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { environment } from '../environments/environment'; @Component({ selector: 'app-tab-page', templateUrl: './tab-page.component.html' }) export class TabPageComponent implements OnInit { isProduction = environment.production; userId: string; fileName: string; constructor(private route: ActivatedRoute) {} ngOnInit() { // 从路由参数中获取userId和fileName(根据你的实际传参方式调整) this.userId = this.route.snapshot.queryParamMap.get('userId'); this.fileName = this.route.snapshot.queryParamMap.get('fileName'); } }
- 在模板中使用属性绑定:
<script [src]="isProduction ? '../rest/project1/getSource/' + userId + '/' + fileName : 'rest/project1/getSource/' + userId + '/' + fileName"></script>
这样就能完美实现根据environment.production自动切换路径的需求啦!
内容的提问来源于stack exchange,提问作者Elydasian
相关产品推荐
相关产品推荐

