absolute paths not recommended in jsps

答案网址:https://stackoverflow.com/questions/15759549/jsp-absolute-paths


Could someone explain why absolute paths not recommended to use in JSP (e.g., IntelliJ IDEA show me a warning)?enter image description here

share improve this question
 
1 
Because IntelliJ is smart enough to realize that you should always use a path that's relative to the root of your web context. –  duffymo Apr 2 '13 at 8:40
 
So there is no strict rule to use only relative or context-based paths? –  sidlejinks Apr 2 '13 at 8:45
 
There are no rules, my friend. Write it any way you want and live with the consequences. –  duffymo Apr 2 '13 at 9:15

up vote 19 down vote accepted

Consider the following code in your JSP:

<script src="/path/to/script.js" />

And you deploy your application on www.example.com in servlet context myContext, your script will be looked up by the browser in

www.example.com/path/to/script.js

However, the browser will not find the script. The URL where it can actually be found containts the servlet context as well as part of the URL:

www.example.com/myContext/path/to/script.js

So you should change the URL in your JSP to:

<script src="${pageContext.request.contextPath}/path/to/script.js" />

Then the context path is also available in the URL and everything will work fine.

share improve this answer
 
 
Thank you very much indeed for explanation! –  sidlejinks Apr 2 '13 at 9:45
 
This didn't work at all for me. It just rendered files with the path looking something like: localhost:8080/profile/$%7BpageContext.request.context%7D/cs‌​s/profile/ –  Matt Powell Jul 17 '13 at 20:36
 
@MattPowell seems like your expression ${...} did not get evaluated right. Some frameworks require to use #{...} instead, did you try that? –  Uooo Jul 22 '13 at 5:46
 
@w4rumy Thanks. It turns out I was using an outdated version of JSP. Once I updated to the latest version, the syntax worked correctly. –  Matt Powell Jul 22 '13 at 15:42
 
Probably we can just write path/to/script.js without any prepending slash or context variable, am I right? –  ieXcept Apr 9 '16 at 18:17

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值