How to link a web resource file from /main/resources in JSP?

后端 未结 2 1950
南旧
南旧 2021-01-05 08:38

I have the following structure in my java webapp

-- main
   -- java
   -- resources
      -- lib
         -- css
            -- style.css
   -- webapp
               


        
相关标签:
2条回答
  • 2021-01-05 08:47

    The Maven /main/resources folder is for classpath resources which do not represent Java classes, such as i18n properties files and all kinds of configuration files (text, xml, json, etc). It are exactly those resources you'd like to obtain via ClassLoader#getResourceAsStream().

    That folder is not intented for public web resources (i.e. files which are accessible by a public http://xxx URL). You're supposed to put those web resource files in Maven /main/webapp folder (outside /WEB-INF and /META-INF), like as you already correctly did for the JSP file (which is also a public web resource).

    So, simply move that /lib folder down (I'd personally also rename that folder to e.g. "resources", "assets", or "static", which is more conform the de facto standards; a "lib" folder name namely suggests that it's full of JAR files).

    main
     |-- java
     |-- resources
     `-- webapp
          |-- lib
          |    `-- css
          |         `-- style.css
          |-- WEB-INF
          |    `-- web.xml
          `--index.jsp
    

    Given this structure, an example deployment context path of /webapp, and an example server running on http://localhost:8080, the CSS file should be accessible on below absolute URL:

    http://localhost:8080/webapp/lib/css/style.css

    So, any of the below CSS links in the HTML representation of the JSP page should do:

    <link rel="stylesheet" href="http://localhost:8080/webapp/lib/css/style.css" />
    
    <link rel="stylesheet" href="//localhost:8080/webapp/lib/css/style.css" />
    
    <link rel="stylesheet" href="/webapp/lib/css/style.css" />
    
    <link rel="stylesheet" href="${pageContext.request.contextPath}/lib/css/style.css" />
    

    Take your pick. The last one is recommendable given the dynamicness of the other parts of the target URL.

    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
    0 讨论(0)
  • 2021-01-05 09:07

    You need to put assets that are to be delivered to the client under your webapp directory. Otherwise you will need to write a servlet to deliver them.

    You can find all the nitty details in Chapter 10 of the Java Servlet 3.1 Specification.

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