JavaServer Faces

A new face on application development in Java

‡ What is JSF?
± It is a web development open source framework.

‡ Why JSF is Required?
± To build a Event based application and also to reduce development time of application.

‡ How does it Works?
± It works majorly on the MVC design principle. ± Uses the EL as well as Events

What is JSF?
‡ JSF is an open standard: JSR 127 ‡ Java Community Process Website: ‡ JSF is included in Java EE (formerly known is J2EE)

Why JSF is Required? 
JSF is a new and upcoming web application framework that accomplishes the MVC paradigm It is similar to Struts but has features and concepts that are beyond those of Struts - especially the component orientation.  Provides set of reusable custom components.  Provides set of JSP tags to access those components.  Event driven model  Eliminate a great deal of hand coding  Make is easy for non-J2EE programmers

How does JSF works? 
JSF follows MVC framework Model: objects and properties of application View: Renderers take care of view. Controller: Faces Servlet/ JSF infrastructure defines the flow of the application.

Comparison between JSF and Struts



High level overview of JSF

Login page


Welcome page


Example files
index.jsp,welcome.jsp define the login and welcome screens. manages user data faces-config.xml configuration file for the application. web.xml deployment descriptor.


JSF Example(index.jsp)
<%@ taglib uri="" prefix="f" %> <%@ taglib uri="" prefix="h" %> <f:loadBundle basename=³com.corejsf.bundle.Messages" var="Message"/> <f:view> « <h:form> <h3><h:outputText value="#{Message.inputname_header}"/></h3> <table> <tr> <td>Name:</td> <h:inputText value="#{}³ required=³true´/> <f:validateLength minimum="2" maximum="20"/> « <td>Password:</td> <h:inputSecret value="#{user.password}"/> « <h:commandButton value="Login" action="login"/> </h:form> </f:view>

‡ Tag Libraries: core and html.
<%@ taglib uri="" prefix="h" %> <%@ taglib uri="" prefix="f" %>

‡ Core tags are used to perform core actions and display nothing to the user. Html tags are used to render html elements(text, form elements etc) to the user. ‡ <f:loadBundle> is a core tag. Loads properties file and makes it value available to variable message.
<f:loadBundle basename= com.corejsf..bundle.Messages" var="Message"/>

‡ All JSF components must be nested inside <f:view> core tag.
<f:view> <h:form> <h3><h:outputText value="#{Message.inputname_header}"/></h3> <h:inputText value="#{}³ required=³true´/> <f:validateLength minimum="2" maximum="20"/> <h:inputSecret value="#{user.password}"/> <h:commandButton value="Login" action="login"/> </h:form> </f:view>


Example (Cntd.)
‡ Any attribute value that starts with # and is wrapped in {} is dynamically substituted in

‡ <h:form> represents form element ‡ Form action is defined in the <h:commandButton> element.
<h:commandButton value="Login" action="login"/>

‡ <h:inputText> for name field renders a textbox. Required attribute tells the value must be provided by the user. Thus validating the field.
<h:inputText value="#{user.userName}" required="true">

‡ Nested core tag provides range validation.
<f:validateLength minimum="2" maximum="20"/>

public class UserBean { .. public String login(){ .. return login ; } public String getName() { . . . } public void setName(String newValue) {. . . } public String getPassword() { . . . } public void setPassword(String newValue) { . . . } ... }

Configuration file (faces-config.xml)
<?xml version="1.0"?> <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN" ""> <faces-config> <navigation-rule> <from-view-id>/index.jsp</from-view-id> <navigation-case> <from-outcome>login</from-outcome> <to-view-id>/welcome.jsp</to-view-id> </ navigation-case> </navigation-rule> <managed-bean> <managed-bean-name>user</managed-bean-name> <managed-bean-class>com.corejsf.UserBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> </faces-config>


Configuration File(Cntd.)
‡ faces-config.xml defines how one page will navigate to next. Also specifies managed beans.
<navigation-rule> <from-view-id>/index.jsp</from-view-id> <navigation-case> <from-outcome>login</from-outcome> <to-view-id>/welcome.jsp</to-view-id> </navigation-case> </navigation-rule

‡ <from-view-id> page you are currently on. ‡ <to-view-id> next page to display. ‡ <from-outcome> value matches the action attribute of the command button of index.jsp
<h:commandButton value="Login" action="login"/>


Configuration file (Cntd.)
‡ Managed bean is the model of the framework. ‡ <managed-bean-name> is the name the views use to reference the bean.<managed-bean-name>user</managed-bean-name>
<h:inputText value="#{}³ required=³true´/>

‡ <managed-bean-class> is the fully classified name for the bean.
<managed-bean-class> com.corejsf.UserBean </managed-bean-class> <managed-bean-scope>session</managed-bean-scope>


Web.xml (Deployment Descriptor)
<context-param> <param-name> javax.faces.CONFIG_FILES</param-name> <param-value> /WEB-INF/faces-config.xml </param-value> <description> </description> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class> javax.faces.webapp.FacesServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern *.faces </url-pattern> </servlet-mapping>


Web.xml (Cntd.)
‡ Javax.faces.CONFIG_FILES parameter tells where the JSF configuration file exists.
<param-name> javax.faces.CONFIG_FILES </param-name> <param-value> /WEB-INF/examples-config.xml </param-value>

‡ Javax.faces.STATE_SAVING_METHOD specifies where the state must be saved: client or server.
<param-name> javax.faces.STATE_SAVING_METHOD </param-name> <param-value>server</param-value>

‡ The servlet-mapping and servlet blocks specify that any URL that ends in a .jsf extension should be redirected through a servlet called javax.faces.webapp.FacesServlet.


Life cycle of JSF


JSF Tags
‡ JSF application typically uses JSP pages to represent views. JSF provides useful special tags to enhance these views. Each tag gives rise to an associated component. JSF provides 43 tags in two standard JSF tag libraries: ‡ JSF Core Tags Library and ‡ JSF Html Tags Library ‡ Even a very simple page uses tags from both libraries. ‡ <%@ taglib uri= prefix= f %> <%@ taglib uri= prefix= h %> <f:view> <h:form> </h:form> </f:view>

What is Apache MyFaces?
‡ First free open source implementation of JSF. ‡ Provides rich set of prefabricated components. ‡ Tomahawk Original MyFaces component library. ‡ <%@ taglib uri="" prefix="t"%> ‡ Tobago Apache Library now under MyFaces umbrella. ‡ Trinidad Originally Oracle ADF components.

JSF Tags

‡ JSF HTML Tag Reference html tags provided in JSF. ‡ JSF column Tag Used for creating columns of a table. This tag creates a data column inside a data table. <h:dataTable border="1"> <f:facet name="header"> <h:outputText value="This is header."/> </f:facet> <h:column> <f:facet name="header"> <h:outputText value="Student"/> </f:facet> </h:column> ‡ JSF commandButton Tag This tag renders an HTML submit button. This button can be associated with bean. ‡ <h:commandButton image="/unprotected/images/buttons/finish.JPG" id="pmsfinishbutton" value="Finish" title="FINISH" type="" action="#{}" onclick="return submitdisableButton('pmsfinishbutton');" />

‡ JSF commandLink Tag JSF commandLink tag which is rendered as a anchor tag. ‡ <h:commandLink value="Modify Existing Ticker Items" style="color: red" action="#{TickerHelperBean.allTickerResponse}"/> ‡ JSF dataTable Tag This tag is used to create table on the page. The component is rendered as an html <table> element. ‡ JSF form Tag This tag renders html form element which contains the data that is submitted with the form. This tag uses "POST" method. <h:form id="tvhardware"> </h:form>


JSF graphicImage Tag This displays the image on the page. This tag renders an html "img" element. ‡ <t:graphicImage value="/unprotected/images/content_heading_arrow.jpg" width="19" height="33"/>

JSF inputHidden Tag This tag is used to create the field that is invisible to the user. ‡ <h:inputHidden binding="#{Navigation.currentPage}" value="AppointmentScheduling"/> ‡ JSF inputSecret Tag This tag is used to create a text box for having password that is secret. ‡ JSF inputText Tag This tag is used to create html input element which has the type "text". It creates input text field where text can be entered. ‡ <t:inputText id="searchCriteria" value="#{organisationManagementMB.searchOrganisationHelper.searchCr iteria}" /> ‡ JSF inputTextarea Tag This tag is used to render html "textarea" element . It creates input text area where text can be entered in multiple lines.


JSF message Tag This is used to display the most recent message for the component.

JSF messages Tag This tag is also like message tag which is also used to show all messages for the components. If you want to customize the message then CSS can be used. <t:panelGrid columns="1" border="0" cellspacing="1" columnClasses="footercolumnClass1,footercolumnClass2,footercolumnClass3"> <h:messages layout="list" errorClass="labelsnonmandatory" errorStyle="color:red" showDetail="true"/> <t:panelGrid width="100%" id = "errorHeader" cellspacing="0" align="center" > <t:outputText value="Errors : " styleClass="error_messages"/> </t:panelGrid> <t:panelGrid/>

JSF outputFormat Tag This tag is used for showing output with the parameterized text that facility allows you to customize the appearance of the text using CSS styles also. <h:outputFormat escape="false" value="#{mess.message}" styleClass="labelsnonmandatory" style="color:red"></h:outputFormat> <h:outputFormat value="Hello, {0} !"> <f:param value="chandan"/> </h:outputFormat> This tag is used for creating component for displaying formatted output as text.


JSF outputLabel Tag This is the outputLabel tag which show the text labeled with the specific component created in your application. <t:outputLabel value="Report Type : styleClass="labelsnonmandatory"/> JSF outputLink Tag This is the outputLink which show the output text holding a link of a page or a website location. This link is similar from the link created by the JSF commandLink tag text. <h:outputLink styleClass="ordercart_lable2" value="#{request.contextPath}/servlet/printing?contractNo=#{item.contra ctID} onclick ="setBunload(false);" >Print</h:outputLink> JSF outputText Tag <h:outputText styleClass="labelsnonmandatory" value=" #{helper.appointmentSearchString}" rendered="#{helper.orderItemCapture.orderItem.orderItemAppointmentT O!=null}"/>



JSF panelGrid Tag This tag is used create compound component that is used to layout other components. This tag renders html table with specified no. of columns. <t:panelGrid width="100%" columns="3" columnClasses="td_heading1,td_heading2" cellspacing="0" cellpadding="0"> <t:graphicImage value="/unprotected/images/content_heading_arrow.jpg" width="19" height="33"/> <t:panelGroup> <t:outputLabel value="Create New Mobile Customer"/> <a4j:status startText="Updating..." startStyleClass="labels"/> </t:panelGroup> </t:panelGrid> JSF panelGroup Tag This is used to create a component that acts as a container to group a set of components. All these components are under one component or can say one parent. JSF selectBooleanCheckbox Tag selectBooleanCheckbox tag is used to create checkbox. <t:selectBooleanCheckbox id="checkbox1" value="#{orderCapture.salesOrder.customerDetailsTO.companyMemorandumProvi ded}"></t:selectBooleanCheckbox>

JSF selectManyCheckbox Tag It is used to provide the user to select many items from a list of options. The user can select one or more options. JSF selectManyMenu Tag This is used to select more than one items from a set of options. JSF selectOneMenu Tag This is used to display the element that enables the user to select only one among the list of available options. <t:selectOneMenu id ="noofsignatories" value="#{orderCapture.customerDetailsHelper.numberOfSignatorie s}" > <a4j:support event="onchange" reRender="signatories" ajaxSingle="true" /> <f:selectItem id="selectitem1" itemLabel="1" itemValue="1"></f:selectItem></t:selectOneMenu>

JSF selectOneRadio Tag This allows the user to select one option from a set of available options. <h:selectOneRadio id="activeProfile" value="#{TariffLinkManaged.selectedProfile}" styleClass="labels" layout="lineDirection" > <f:selectItems id="selectedProfile" value="#{TariffLinkManaged.profileOptions}" /> </h:selectOneRadio>

All JSF Core Tags: f :view Creates the top-level view f:subview Creates a subview of a view <f:view> <t:panelLayout id="page" layout="classic" width="1000" cellpadding="0" border="0" align="center" bodyClass="panel_body" navigationClass="panel_leftnav" > <f:facet name="header"> <f:subview id="header"> <%@ include file="/protected/subpages/header.jsp"%> </f:subview> </f:facet> <f:facet name="navigation"> <f:subview id="menu"> <%@ include file="/protected/subpages/leftShoppingCart.jsp"%> </f:subview> </f:facet>

<f:facet name="body"> <f:subview id="body1" rendered="true"> <%@ include file="/protected/additionalorderitems/subpages/sub_activatemalici ouscalltracing.jsp"%> </f:subview> </f:facet> <f:facet name="footer"> <f:subview id="footer"> <%@ include file="/protected/subpages/footer.jsp"%> </f:subview> </f:facet> </t:panelLayout> </f:view>

‡ f:param Constructs a parameter component ‡ <t:commandLink value="Modify discount schemes" type="submit" action="#{organisationManagementMB.modifyOrganisationDiscounts}" styleClass="black_link" > ‡ <f:param name="selectedOrganisationForModification" value="#{record.organisationId}" /> ‡ </t:commandLink> ‡ f:attribute Adds an attribute to a component ‡ <h:commandButton id="button1"> <f:attribute name="value" value="Click"></f:attribute> </h:commandButton>

‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡

f:converter Adds an arbitrary converter to a component <h:inputText id="name"> <f:converter converterId="javax.faces.Short"/> </h:inputText> f:converterDateTime Adds a datetime converter to a component <h:outputText value="#{}"> <f:convertDateTime type="both" dateStyle="short"/> </h:outputText> dateStyle : This is used to set the style of date to be presented to the page. This attribute is applied only if the type attribute is "date" or "both". This attribute can take some values like : default May 14, 2007 2:35:45 PM ( Default Value) short 5/14/07 12:55:42 PM medium May 14, 2007 2:42:36 PM long May 14, 2007 2:41:08 PM full Monday, May 14, 2007 2:39:56 PM f:converterNumber Adds a number converter to a component This class is responsible to convert String to java.util.Number object and vice-versa. f:actionListener Adds an action listener to a component <h:commandButton id="button1" value="Click"> <f:actionListener type= test.MyBean" /> </h:commandButton> public class MyBean implements ActionListener,ValueChangeListener{ String som = ""; private Date today = new Date(); public void processAction(ActionEvent e){ J} public void processValueChange(ValueChangeEvent ce){ }


‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ f:valueChangeListener Adds a valuechange listener to a component f:validator Adds a validator to a component <h:inputText id="email" required="true"> <f:validator validatorId="checkvalidemail" /> </h:inputText> f:validateDoubleRange Validates a double range for a component s value f:validateLength Validates the length of a component s value <h:inputSecret id="PWD" value="#{MessageBean.b}" required="true" > <f:validateLength maximum="15" minimum="6"/> </h:inputSecret> f:validateLongRange Validates a long range for a component s value f:facet Adds a facet to a component f:loadBundle Loads a resource bundle, stores properties as a Map <f:loadBundle basename="RB" var="mes"/> <f:view> <html> <body> <h:form> <h:outputText value="#{mes.greeting_text}" /> </h:form> f:selectitems Specifies items for a select one or select many component f:selectitem Specifies an item for a select one or select many component f:verbatim Adds markup to a JSF page

‡ ‡ ‡

Rich Faces
‡ ‡ ‡ ‡ ‡ ‡ RichFaces is a rich component library for JSF and an advanced framework for easily integrating AJAX capabilities into business application development. which really means..... I don't NEED to know JavaScript.

‡ ‡ ‡ ‡ ‡ ‡

JavaServer Faces + AJAX = JBoss RichFaces Rich JSF Components

‡ A framework designed to add Ajax-functionality to ‡ existing JSF solutions. ‡ JSF tags are augmented with additional RichFaces tags ‡ to provide this special functionality.

<%@ taglib uri="" prefix="a4j"%> <%@ taglib uri="" prefix="h"%> <%@ taglib uri="" prefix="f"%> <html> <head> <title>Repeater </title> </head> <body> <f:view> <h:form> <h:inputText size="50" value="#{bean.text}" > <a4j:support event="onkeyup" reRender="rep"/> </h:inputText> <h:outputText value="#{bean.text}" id="rep"/> </h:form> </f:view> </body> </html>

‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡

package demo; public class Bean { private String text; public Bean() {} public void setText(String text) { this.text = text; } public String getText() { return text; } }

‡ RichFaces has three tags used to fire an Ajax request. ‡ <a4j:commandButton> ‡ <a4j:commandLink> ‡ <a4j:support> ‡ The two first are used to render a button and a link, ‡ respectively, with Ajax-functionality. The support tag is ‡ used to add functionality to an existing component. ‡ AjaxCommandButton: renders a button for submitting a form. ‡ AjaxCommandLink: renders a link for submitting a form. ‡ AjaxCommandSupport: delivers Ajax support for existing ‡ elements (such as e.g. input fields).

By using attributes on the Action Components, it is possible to control how much is sent with the request and what is updated by the response: ajaxSingle: this attribute defines that only that specific component is sent with the request. reRender: a comma separated list of components to be rendered from the response. <h:form> <h:inputText value="#{}" > <a4j:support event="onkeyup" reRender="test" ajaxSingle="true"/> </h:inputText> <h:inputText value="#{person.middleName}"/>

It is possible to integrate custom JavaScript with these components using these two attributes: onsubmit: JavaScript code to execute before the form is sent (e.g. for checking request parameters client side). oncomplete: JavaScript code to execute after the Ajax response has returned (e.g. for post-processing the response). <a4j:outputPanel id="panel"> <h:form> <h:selectOneMenu value="#{bean.text}"> <f:selectItem itemValue="Danmark" itemLabel="Danmark"/> <f:selectItem itemValue="Norge" itemLabel="Norge"/> <f:selectItem itemValue="Sverige" itemLabel="Sverige"/> <a4j:support event="onchange" reRender="panel" onsubmit="if(!confirm( Are you sure that you want to switch country?')) {form.reset(); return false;}" oncomplete="alert( The value was saved server-side!')"/> </h:selectOneMenu> <br/> <h:outputText value="#{bean.text}"/>

In general, data being sent in a RichFaces request will be delimited by a form tag (<a4j:form> or <h:form>). When the server receives the request, the contents of it will be decoded by the Faces servlet, which leads the JSF component tree to be updated. Then the response is sent back to the client through the RichFaces renderkit. The decode process, however, does take up a reasonable amount of resources. The tag <a4j:region> is useful for delimiting the number of components to decode, reducing the performance hit. Note that the entire contents of the form is still sent in the request (and received in the response) but only the region is processed.

Output Components
RichFaces offers certain components to render output. These components are output panels Output panels ajaxify a part of the page and makes this part sensitive to changes in the surrounding Ajax Container (region or view root). Transient contents (raw HTML or the JSF <verbatim> tag), which usually is not saved in the component tree, will be added to the tree anyway for quick access. The tag <a4j:outputPanel> is used for this or the class HtmlAjaxOutputPanel. The tag generated a <span> or <div> tag in the client depending on the value of the attribute layout.

Status indicator for Ajax requests
With the tag <a4j:status> the user can be notified of the state of a current Ajax request. Programmatically, the class HTMLAjaxStatus is used: The element has attributes representing text and style to be shown at start (Ajax transfer in progress) and stop (no Ajax request being processed currently), respectively these are named startText and stopText. Alternatively, JSF facets provide the same effect: <a4j:status startText="Progress" stopText="Done" for="stat1"> <a4j:status for="stat2"> <f:facet name="start"> <h:graphicImage value="ajax_process.gif" /> </f:facet> <f:facet name="stop"> <h:graphicImage value="ajax_stoped.gif" /> </f:facet> </a4j:status

Custom Components
‡ Extend a UIComponent
± Create a class that extends UIComponent ± Save the component state ± Register the component with faces-config.xml

‡ Define the renderer or implement inline
± Override encode ± Override decode ± Register the renderer with faces-config.xml

‡ Create a custom tag that subclasses UIComponentTag
± Return the renderer type ± Return the component type ± Set up properties that might use JSF expressions

‡ import; import javax.faces.component.UIOutput; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; ‡ public class LabelComponent extends UIOutput{ private String label; public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } ...

‡ @Override public Object saveState(FacesContext context) { Object values[] = new Object[2]; values[0] = super.saveState(context); values[1] = label; return ((Object) (values)); } ‡ @Override public void restoreState(FacesContext context, Object state) { Object values[] = (Object[])state; super.restoreState(context, values[0]); label = (String)values[1]; }

‡ <faces-config> <component> <componenttype>simple.Label</component-type> <component-class> arcmind.simple.LabelComponent </component-class> </component>

‡ public class LabelComponent extends UIOutput{ ... public void encodeBegin(FacesContext context) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.startElement("label", this); writer.write(label); writer.endElement("label"); writer.flush(); } ... }

‡ public class LabelComponent extends UIOutput{ ... public String getFamily(){ return "simple.Label"; } ... } ‡ public void encodeEnd(FacesContext context) throws IOException { return; } public void decode(FacesContext context) { return; }

‡ [] public class LabelTag extends UIComponentTag { ‡ protected void setProperties(UIComponent component) { /* you have to call the super class */ ‡ super.setProperties(component); ((LabelComponent)component).setLabel(label ); }

‡ <taglib> <tlib-version>0.03</tlib-version> <jspversion>1.2</jsp-version> <shortname>arcmind</short-name> <uri></u ri> <description>ArcMind tags</description> <tag> <name>slabel</name> <tagclass>arcmind.simple.LabelTag</tag-class> <attribute> <name>label</name> <description>The value of the label</description> </attribute> </tag> ...

‡ [test.jsp] <%@ taglib prefix="arcmind" uri="" %> ... <arcmind:slabel label="Form Test"/>


Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.