2011-03-25 58 views
8

我是新来的JavaServer Faces和我试图做到以下几点:加载图像在JSF 2.0

模板文件“/template.xhtml”加载使用

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

在这一CSS文件我想链接到的图像,像这样:

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

如何引用图像(我应该怎么写进去LINK_TO_MY_IMAGE)? 我已经尝试使用直接链接(/contextroot/resources/images/foo.png)和JSF资源记法(/contextroot/faces/javax.faces.resource/foo.png?ln=images) 。

我的目录结构:

/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 

所以,到目前为止,我的问题是,我总是得到一个“404未找到”加载的图像。

回答

7

添加CSS到您的XHTML

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

和CSS

background-image: /resources/images/someName.png 
+0

你是对的,谢谢。我只是在我的CSS文件中有一个错字 – 2011-03-25 09:59:24

+0

但是...在开始时添加“/”不会将此引用为上下文根y Tomcat?我的意思是。如果您的应用程序部署在/myapplication下,该解决方案是否可以工作?在此先感谢 – frandevel 2011-11-30 22:38:19

8

多次实验这部作品在CSS后:

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

在上面, msgError.gif是我的资源位于/resources/images/msgError.gif 我相信.xhtml只是用来使用JSF FacesServlet的(见web.xml中)

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

的“LN”是库名称。

+14

您应该使用'#{resource}'。另见http://stackoverflow.com/questions/6925733/changing-the-image-of-a-hcommandbutton-using-css/6926193#6926193 – BalusC 2011-08-17 11:10:09

+0

感谢您的提示和链接! – 2012-01-10 03:30:40

0

我不知道为什么有这么多不同的方式......但这里是另一种与内联CSS一起工作的路径。

<div style="background-image: url('/javax.faces.resource/images/someName.png.xhtml');"> 
    Text to Display 
</div> 
0

SASS(SCSS)混入

//----------------------------------------------------------------------------- 
// 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}']})"; 
} 

用法:

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