How to use relative paths without including the context root name?

后端 未结 1 1777
抹茶落季
抹茶落季 2020-11-22 11:36

To working my static file (CSS, JS) I have to write absolute path like /AppName/templates/style/main.css. Is there any solution, that I could write relative pat

1条回答
  •  孤城傲影
    2020-11-22 11:44

    If your actual concern is the dynamicness of the webapp context (the "AppName" part), then just retrieve it dynamically by HttpServletRequest#getContextPath().

    
        
        
        
    
    
        link
    
    

    If you want to set a base path for all relative links so that you don't need to repeat ${pageContext.request.contextPath} in every relative link, use the tag. Here's an example with help of JSTL functions.

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    ...
    
        ${pageContext.request.requestURL}
        
        
        
        
    
    
        link
    
    

    This way every relative link (i.e. not starting with / or a scheme) will become relative to the .

    This is by the way not specifically related to Tomcat in any way. It's just related to HTTP/HTML basics. You would have the same problem in every other webserver.

    See also:

    • Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
    • Is it recommended to use the html tag?

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