Any clever ways of handling the context in a web app?

前端 未结 13 1517
一整个雨季
一整个雨季 2020-12-02 13:37

In Java, web apps are bundled in to WARs. By default, many servlet containers will use the WAR name as the context name for the application.

Thus myapp.war gets depl

13条回答
  •  甜味超标
    2020-12-02 13:39

    For HTML pages, I just set the HTML tag. Every relative link (i.e. not starting with scheme or /) will become relative to it. There is no clean way to grab it immediately by HttpServletRequest, so we need little help of JSTL here.

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

    This has in turn however a caveat: anchors (the #identifier URL's) will become relative to the base path as well. If you have any of them, you would like to make it relative to the request URL (URI) instead. So, change like

    jump
    

    to

    jump
    

    In JS, you can just access the element from the DOM whenever you'd like to convert a relative URL to an absolute URL.

    var base = document.getElementsByTagName("base")[0].href;
    

    Or if you do jQuery

    var base = $("base").attr("href");
    

    In CSS, the image URLs are relative to the URL of the stylesheet itself. So, just drop the images in some folder relative to the stylesheet itself. E.g.

    /css/style.css
    /css/images/foo.png
    

    and reference them as follows

    background-image: url('images/foo.png');
    

    If you rather like to drop the images in some folder at same level as CSS folder

    /css/style.css
    /images/foo.png
    

    then use ../ to go to the common parent folder

    background-image: url('../images/foo.png');
    

    See also:

    • Is it recommended to use the html tag?

提交回复
热议问题