In the previous two recipes, we have specified the desired styles between quotes as static CSS. In this recipe, we will use dynamic CSS, which means that we will let a managed bean provide the desired styles and we will use EL to collect them.
We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.
First we develop a managed bean that is capable of returning CSS styles depending on our business logic. Actually, our bean returns CSS class names as shown next (you may also return CSS styles):
package bean; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; @ManagedBean @RequestScoped public class Bean { private String messageProperty = "message"; private String messageFontProperty = "message-font"; private String oddevenProperty = "odd, even"; public String getMessageProperty() { return messageProperty; } public void setMessageProperty(String messageProperty) { this.messageProperty = messageProperty; } public String getMessageFontProperty() { return messageFontProperty; } public void setMessageFontProperty(String messageFontProperty) { this.messageFontProperty = messageFontProperty; } public String getOddevenProperty() { return oddevenProperty; } public void setOddevenProperty(String oddevenProperty) { this.oddevenProperty = oddevenProperty; } }
Now the JSF page defines the CSS classes, and uses EL to collect their names from bean:
<?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:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <title>JSF and CSS example</title> <style type="text/css"> .message { text-align: left; letter-spacing:5px; color:#000099 } .message-font { font-family:georgia,garamond,serif; font-size:20px; font-style:italic; } .odd { background-color: blue } .even { background-color: red } </style> </h:head> <h:body> <h:form> <h:panelGrid columns="3" border="1" footerClass="#{bean.messageProperty}" headerClass="#{bean.messageFontProperty}" rowClasses="#{bean.oddevenProperty}" title="PanelGrid and CSS"> <f:facet name="header"> <h:outputText value="Fill Names Below"/> </f:facet> <h:inputText/> <h:inputText/> <h:inputText/> <h:inputText/> <h:inputText/> <h:inputText/> <h:inputText/> <h:inputText/> <h:inputText/> <h:inputText/> <h:inputText/> <h:inputText/> <f:facet name="footer"> <h:outputText value="The End"/> </f:facet> </h:panelGrid> </h:form> </h:body> </html>