8

I am new to JavaServer Faces and I'm trying to do the following:

The template file "/template.xhtml" loads a stylesheet using

<h:outputStylesheet library="style" name="default.css" />

Within that CSS file I want to link to images like so:

... background-image: url(LINK_TO_MY_IMAGE) ...

How do I reference that image (what should I write into LINK_TO_MY_IMAGE)? I already tried to use the direct link (/contextroot/resources/images/foo.png) and the JSF resources notation (/contextroot/faces/javax.faces.resource/foo.png?ln=images).

My directory structure:

/resources/images  => contains image files
/resources/style/default.css
/WEB-INF/web.xml
/WEB-INF/faces-config.xml
/template.xhtml
/demoPage.xhtml  => uses the template.xhtml

So, my problem so far is that I always get a "404 Not Found" for loading that images.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Jan Bunschoten
  • 83
  • 1
  • 1
  • 3

4 Answers4

8

After much experimentation this works in the CSS:

url("msgError.gif.xhtml?ln=images")

In the above, msgError.gif is my resource located at /resources/images/msgError.gif I believe the .xhtml is just used to use the JSF FacesServlet (see web.xml)

<servlet-mapping>
  <servlet-name>FacesServlet</servlet-name>
  <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

The "ln" is the library name.

Domenic D.
  • 5,276
  • 4
  • 30
  • 41
  • 14
    You should be using `#{resource}`. See also http://stackoverflow.com/questions/6925733/changing-the-image-of-a-hcommandbutton-using-css/6926193#6926193 – BalusC Aug 17 '11 at 11:10
7

Add css into your XHTML

<link href="#{facesContext.externalContext.requestContextPath}/resources/style/default.css" rel="stylesheet" type="text/css" />

and in CSS

background-image: /resources/images/someName.png
palacsint
  • 28,416
  • 10
  • 82
  • 109
jmj
  • 237,923
  • 42
  • 401
  • 438
  • You're right, thanks. I just had a typo in my CSS file .. – Jan Bunschoten Mar 25 '11 at 09:59
  • But... adding a "/" at the begining wouldn't reference this as the context root y Tomcat? I mean. If you have the application deployed under /myapplication, would this solution work? Thanks in advance – frandevel Nov 30 '11 at 22:38
0

I don't know why there are so many different ways... but here is another path that works with inline CSS.

<div style="background-image: url('/javax.faces.resource/images/someName.png.xhtml');">
    Text to Display
</div>
Steve Jones
  • 1,528
  • 19
  • 12
0

SASS (SCSS) mixin

//-----------------------------------------------------------------------------
// resource_url function returns the parameter as url(#{resource['<parameter>']})
// and should be used instead of CSS url() or compass image_url() in JSF applications.
// Define JSF Resource Library resource['standard:

@function resource_url($url) {
  @return url + "(\#{resource['test:#{$url}']})";
}

Usage:

background: resource_url('img/footer_trenner.gif') no-repeat center left;
user853553
  • 51
  • 4