How to include cascading style sheets (CSS) in JSF

In JSF 2.0, you can use <h:outputStylesheet /> output a css file.

For example,

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

It will generate following HTML output…

<link type="text/css" rel="stylesheet" 
	href="/JavaServerFaces/faces/javax.faces.resource/style.css?ln=css" />

JSF outputStylesheet example

An example to show the use of JSF 2 <h:outputStylesheet /> to render a “style.css” file, locate in the “resources/css” folder, see figure below :
jsf2-outputStylesheet-example

JSF file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      >
    <h:head></h:head>
    <h:body>
    	
    	<h1>JSF 2 outputStylesheet example</h1>
    	
    	<h:outputStylesheet library="css" name="style.css"  />
    	
    	<div class="red">This is red color</div>
    	
    </h:body>
    
</html>

It will generate following HTML output

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<link type="text/css" rel="stylesheet" 
		  href="/JavaServerFaces/faces/javax.faces.resource/style.css?ln=css" />
	</head>
	
	<body>
    	
    	   <h1>JSF 2 outputStylesheet example</h1>
    	
    	   <div class="red">This is red color</div>
		
	</body>

</html>

Warning
When render CSS file via <h:outputStylesheet /> tag, remember put the <h:head /> tag as well; Otherwise the css file will not be included.

原文地址:https://www.cnblogs.com/ghgyj/p/4765393.html