JSP absolute paths

2020-03-08 13:12发布

问题:

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.