Could someone explain why absolute paths not recommended to use in JSP (e.g., IntelliJ IDEA show me a warning)?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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.