Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the following structure in my java webapp

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

How can I link the style.css to my index jsp?

<link rel="stylesheet" href="???">

What should be here?

Thanks in advance

like image 850
Carmine Avatar asked Jun 25 '15 13:06

Carmine


2 Answers

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
like image 131
BalusC Avatar answered Nov 18 '22 12:11

BalusC


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.

like image 30
Steve C Avatar answered Nov 18 '22 11:11

Steve C