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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With