Retrieving relative url path of file inside a include file, jsp

后端 未结 1 1990
再見小時候
再見小時候 2021-01-03 10:59

I have a file called Main.jsp, located at the absolute url path of \"http://Mywebpage.com/Open/This/Folder/Main.jsp\".

Inside Main.jsp, there is a jsp include:

相关标签:
1条回答
  • 2021-01-03 11:31

    The <script src> is relative to the current request URL (as you see in browser address bar), not to the server side location of the JSP file. It's namely the webbrowser who needs to load the script, not the webserver.

    So, if the current request URL is

    http://Mywebpage.com/Open/This/Folder/Main.jsp

    and the JS file is actually located in

    http://Mywebpage.com/HL.js

    then you need to reference it as

    <script type="text/javascript" src="/HL.js"></script>
    

    The leading slash will make it relative to the domain root.

    However, if your webapp is not deployed on the domain root per se, but on a context path, such as /Open in your (oversimplified) example, and your JS file is actually located in

    http://Mywebpage.com/Open/HL.js

    then you need to prepend the URL with HttpServletRequest#getContextPath().

    <script type="text/javascript" src="${pageContext.request.contextPath}/HL.js"></script>
    

    This will end up as (rightclick page in browser, do View Source to see it)

    <script type="text/javascript" src="/Open/HL.js"></script>
    

    See also:

    • How to use relative paths without including the context root name?
    • Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

    Update: as per your update, please note that this does not apply on TLD files since they are been resolved on the server side. Normally, you should drop TLD files in /WEB-INF folder and reference it by uri="/WEB-INF/filename.tld".

    0 讨论(0)
提交回复
热议问题