Snowy Coder Girl
Snowy Coder Girl

Reputation: 5518

Style Paths In Java EE Applications

I have a Java EE application and in the application I have the following structure.

WEB-INF
    layout
        header.jsp
    styles
        main.css

I want to include the main.css in the header.jsp. Which I am attempting to do with the following (where ... is the path):

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

However, I can't seem to get the right path. I have tried each of the following with no luck:

../styles/main.css
/styles/main.css
styles/main.css
/WEB-INF/styles/main.css
WEB-INF/styles/main.css

What is the correct path?

Upvotes: 1

Views: 9231

Answers (1)

BalusC
BalusC

Reputation: 1108702

First of all, resources in /WEB-INF folder are not directly publicly accessible without a intermediating (front controller) servlet (this also covers JSP files themselves! the <jsp:include> runs at webserver, not at webbrowser). So you've to put CSS (and JS and image) files outside the /WEB-INF folder.

WebContent
 |-- WEB-INF
 |    `-- layout
 |         `-- header.jsp
 |-- styles
 |    `-- main.css
 :

Assuming that it's now in /styles/main.css, then you can reference it as follows:

<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/styles/main.css" />

Using ${pageContext.request.contextPath} (which prints the current context path with a leading slash and thus makes the CSS URL guaranteed relative to the domain root) is not necessary per se, but it is your safest bet as the current request URL is unknown. All relative paths in HTML <link>, <script>, <img>, <a>, etc elements are namely namely by the webbrowser resolved relative to the current request URL (as you see in browser's address bar). As long as it's unclear what your request URL is, I can't answer the right CSS path without using ${pageContext.request.contextPath}.

See also:

Upvotes: 14

Related Questions