JavaServer Faces -
  • No tags were found...

JavaServer Faces -

#21Brought to you facts at your fingertipsJavaServer Faces Get More Refcardz! Visit refcardz.comCONTENTS INCLUDE:nDevelopment Processn LifecyclenFaces-config.xmlnThe JSF Expression LanguagenJSF Core TagsnJSF HTML Tags and more...ABOUT THIS REFCARDJavaServer Faces (JSF) is the “official” component-basedview technology in the Java EE web tier. JSF includes a setof predefined UI components, an event-driven programmingmodel, and the ability to add third-party components. JSFis designed to be extensible, easy to use, and toolable. Thisrefcard describes the JSF development process, standard JSFtags, the JSF expression language, and the faces-config.xmlconfiguration file.DEVELOPMENT PROCESSA developer specifies JSF components in JSF pages,combining JSF component tags with HTML and CSS for styling.Components are linked with managed beans—Java classesthat contain presentation logic and connect to business logicand persistence backends. Entries in faces-config.xml containnavigation rules and instructions for loading managed beans.client devicesJSP Style......servlet containerweb applicationpresentationJSF Pagesapplication logicnavigationvalidationevent handlingManaged BeansJSF frameworkA JSF page has the following structure:Proper XMLbusiness logic......JavaServer FacesdatabasewebserviceBy Cay S. HorstmannThese common tasks give you a crash course into using JSF.Text fieldpage.jspxfaces-config.xmlbean1com.corejsf.SampleBeansessioncom/corejsf/SampleBean.javapublic class SampleBean {public int getLuckyNumber() { ... }public void setLuckyNumber(int value) { ... }...}Buttonpage.jspxfaces-config.xmlsuccess/success.jspxerror/error.jspx→DZone, Inc. |

tech facts at your fingertips2JavaServer FacesButton, continuedcom/corejsf/SampleBean.javapublic class SampleBean {public String login() { if (...) return"success"; else return "error"; }...}Radio buttonspage.jspx

tech facts at your fingertips3JavaServer FacesLIFECYCLEweb.xmlrequestresponseRestoreViewThe faces-config.xml file contains a sequence of the followingentries.n managed-bean1. description , display-name, icon (optional)2. managed-bean-name3. managed-bean-class4. managed-bean-scope5. managed-property (0 or more, other optional choicesare map-entries and list-entries which are notshown here)1. description, display-name, icon (optional)2. property-name3. value (other choices are null-value, map-entries,list-entries which are not shown here)n navigation-rule1. description, display-name, icon (optional)2. from-view-id (optional, can use wildcards)3. navigation-case (1 or more)nfrom-action (optional, not common)nfrom-outcomento-view-idn applicationm resource-bundle1. base-name2. varm action-listener, default-render-kit-id,resource-bundle, view-handler, state-manager, elresolver,property-resolver, variable-resolver,application-extension (details not shown)n converterm converter-idm converter-classm Optional initialization (not shown here)n validatorm validator-idm validator-classm Optional initialization (not shown here)n lifecycleRenderResponsefaces-config.xmlm phase-listenerApply RequestValuesrender responseresponse completeProcesseventsresponse completeProcesseventsInvokeApplicationconversion errors/render responseProcessValidationsresponse completeProcesseventsvalidation or conversion errors/render responsen component, factory, referenced-bean, render-kit,faces-config-extension (details not shown)response completeProcesseventsUpdateModelValuesFaces Servletjavax.faces.webapp.FacesServlet1javax.faces.DEFAULT_SUFFIX.jspxFaces Servlet*.facesindex.facesindex.htmlTHE JSF EXPRESSION LANGUAGE (EL)An EL expression is a sequence of literal strings and expressionsof the form base[expr1][expr2]... As in JavaScript, youcan write base.identifier instead of base['identifier'] orbase["identifier"]. The base is one of the names in the tablebelow or a name defined in faces-config.xml.headerheaderValuesparamparamValuescookieinitParamrequestScopesessionScopeapplicationScopefacesContextviewA Map of HTTP header parameters, containing only the firstvalue for each name.A Map of HTTP header parameters, yielding a String[] array ofall values for a given name.A Map of HTTP request parameters, containing only the firstvalue for each name.A Map of HTTP request parameters, yielding a String[] array ofall values for a given name.A Map of the cookie names and values of the current request.A Map of the initialization parameters of this web application.A Map of all request scope attributes.A Map of all session scope attributes.A Map of all application scope attributes.The FacesContext instance of this request.The UIViewRoot instance of this request.DZone, Inc. |

tech facts at your fingertips4JavaServer FacesThe JSF Expression Language (EL), continuedThere are two expression types:Tagn Value expression: a reference to a bean property or anentry in a map, list, or array. calls getName or setName on the userBeanobjectpizza.choices[var] calls pizza.getChoices( ).get(var)or pizza.getChoices( ).put(var, ...)n Method expression: a reference to a method and theobject on which it is to be invoked. Example:userBean.login calls the login method on the userBeanobject when it is invoked.In JSF, EL expressions are enclosed in #{...} to indicatedeferred evaluation. The expression is stored as a string andevaluated when needed. In contrast, JSP uses immediateevaluation, indicated by ${...} delimiters.JSF CORE TAGSf:actionListenerf:valueChangeListenerDescription/ AttributesCreates the top-level viewlocalerenderKitId(JSF 1.2)beforePhase,afterPhaseCreates a subview of a viewbinding, id, renderedAdds a facet to a componentnameAdds an attribute to a componentname, valueConstructs a parameter child componentnamevaluebinding, idAdds an action listener or value change listener to acomponenttypeThe locale for this view.The render kit ID for this viewPhase listeners that are called inevery phase except "restore view"An optional name for this parametercomponent.The value stored in this component.Basic attributesBasic attributesthe name of this facetthe name and value of the attribute to setThe name of the listener classJSF Core Tags, continuedTagf:convertNumberf:validatorf:validateDoubleRangef:validateLongRangef:validateLengthf:loadBundlef:selectitemsf:selectitemDescription/ AttributesAdds a number converter to a componenttypepatternmaxFractionDigitsminFractionDigitsmaxIntegerDigitsminIntegerDigitsintegerOnlygroupingUsedlocalecurrencyCodecurrencySymbolAdds a validator to a componentvalidatorIdValidates a double or long value, or the length of a stringminimum, maximumLoads a resource bundle, stores properties as a MapbasenamevalueThe resource bundle nameThe name of the variable that is bound tothe bundle mapSpecifies items for a select one or select many componentbinding, idvalueBasic attributesValue expression that points to aSelectItem, an array or Collection ofSelectItem objects, or a Map mappinglabels to values.Specifies an item for a select one or select manycomponentbinding, iditemDescriptionitemDisableditemLabelitemValuevaluenumber (default), currency , orpercentFormatting pattern, as defined injava.text.DecimalFormatMaximum number of digits in thefractional partMinimum number of digits in thefractional partMaximum number of digits in theinteger partMinimum number of digits in theinteger partTrue if only the integer part isparsed (default: false)True if grouping separators areused (default: true)Locale whose preferences are tobe used for parsing and formattingISO 4217 currency code to usewhen converting currency valuesCurrency symbol to use whenconverting currency valuesThe ID of the validatorthe minimum and maximum of thevalid rangBasic attributesDescription used by tools onlyBoolean value that sets the item’sdisabled propertyText shown by the itemItem’s value, which is passed to theserver as a request parameterValue expression that points to aSelectItem instancef:setPropertyChangeListener (JSF 1.2)Adds an action listener to a component that sets a beanproperty to a given value.valueThe bean property to set when theaction event occursf:verbatimAdds markup to a JSF pageescaperendered (JSF 1.2)If set to true, escapes , and &characters. Default value is false.Basic attributesbinding, idThe value to set it tof:converterAdds an arbitary converter to a componentconverterIdThe ID of the converterJSF HTML TAGSf:convertDateTimeAdds a datetime converter to a componentTagDescriptiontypedateStyledate (default), time, or bothdefault, short, medium, long, or fullh:formh:inputTextHTML formSingle-line text input controltimeStylepatternlocaletimezonedefault, short, medium, long, or fullFormatting pattern, as defined in java.text.SimpleDateFormatLocale whose preferences are to be usedfor parsing and formattingTime zone to use for parsing andformattingh:inputTextareah:inputSecreth:inputHiddenh:outputLabelMultiline text input controlPassword input controlHidden fieldLabel for anothercomponent for accessibility→DZone, Inc. |

tech facts at your fingertips5JavaServer FacesJSF HTML tags, continuedTagh:outputLinkh:outputFormath:outputTexth:commandButtonh:commandLinkh:messageh:messagesh:grapicImageh:selectOneListboxDescriptionHTML anchorLike outputText, butformats compoundmessagesSingle-line text outputButton: submit, reset, orpushbuttonLink that acts like apushbutton.Displays the most recentmessage for a componentDisplays all messagesDisplays an imageSingle-select listboxregisterAmounttoo muchAmount:'too much' is not anumber.Example: 99Attributes for h:inputText,h:inputSecret, h:inputTextarea,and h:inputHiddenAttributecolsimmediateredisplayrequiredrowsvalueChangeListenerbinding, converter, id, rendered,required, styleClass, value,validatoraccesskey, alt, dir,disabled, lang, maxlength,readonly, size, style,tabindex, titleonblur, onchange, onclick,ondblclick, onfocus,onkeydown, onkeypress,onkeyup, onmousedown,onmousemove, onmouseout,onmouseover, onselectDescriptionFor h:inputTextarea only—number of columnsProcess validation early in the life cycleFor h:inputSecret only—when true, the inputfield’s value is redisplayed when the web page isreloadedRequire input in the component when the form issubmittedFor h:inputTextarea only—number of rowsA specified listener that’s notified of value changesBasic attributesHTML 4.0 pass-through attributes—alt, maxlength,and size do not apply to h:inputTextarea. Noneapply to h:inputHiddenDHTML events. None apply to h:inputHiddenh:selectOneMenuh:selectOneRadioh:selectBooleanCheckboxh:selectManyCheckboxh:selectManyListboxh:selectManyMenuh:panelGridh:panelGrouph:dataTableh:columnSingle-select menuSet of radio buttonsCheckboxMultiselect listboxMultiselect listboxMultiselect menuHTML tableTwo or more componentsthat are laid out as oneA feature-rich tablecomponentColumn in a data tableAttributes for h:outputText andh:outputFormatAttributeescapebinding, converter, id, rendered,styleClass, valueDescriptionIf set to true, escapes , and &characters. Default value is true.Basic at tributesstyle, title HTML 4.0Attributes for h:outputLabelAttributeforbinding, converter, id, rendered,valueDescriptionThe ID of the component to be labeled.Basic attributesAttributes for h:graphicImageBasic AttributesAttributebinding, id, rendered, styleClass, valueDescriptionBasic attributesAttributeidbindingrenderedstyleClassvaluevalueChangeListenerconvertervalidatorrequiredAttributeDescriptionIdentifier for a componentReference to the component that can be used in a backingbeanA boolean; false suppresses renderingCascading stylesheet (CSS) class nameA component’s value, typically a value bindingA method binding to a method that responds to valuechangesConverter class nameAttributes for h:formbinding, id, rendered, styleClassaccept, acceptcharset, dir, enctype, lang,style, target, titleClass name of a validator that’s created and attached to acomponentA boolean; if true, requires a value to be entered in theassociated fieldDescriptionBasic attributesonblur, onchange, onclick, ondblclick, onfocus, DHTML eventsonkeydown, onkeypress, onkeyup, onmousedown,onmousemove, onmouseout, onmouseover, onreset,onsubmitHTML 4.0 attributes(acceptcharset corresponds toHTML accept-charset)alt, dir, height, ismap, lang, longdesc, style,title, url, usemap, widthonblur, onchange, onclick, ondblclick, onfocus,onkeydown, onkeypress, onkeyup, onmousedown,onmousemove, onmouseout, onmouseover,onmouseupAttributes for h:commandButtonand h:commandLinkAttributeactionactionListenercharsetimageimmediateDescriptionHTML 4.0DHTML eventsIf specified as a string: Directly specifies anoutcome used by the navigation handler todetermine the JSF page to load next as a resultof activating the button or link If specified as amethod binding: The method has this signature:String methodName(); the string representsthe outcomeA method binding that refers to a method withthis signature: void methodName(ActionEvent)For h:commandLink only—The characterencoding of the linked referenceFor h:commandButton only—A context-relativepath to an image displayed in a button. If youspecify this attribute, the HTML input’s type willbe image.A boolean. If false (the default), actions and actionlisteners are invoked at the end of the requestlife cycle; if true, actions and action listeners areinvoked at the beginning of the life cycle.DZone, Inc. |

tech facts at your fingertips6JavaServer Facesh:commandButton and h:commandLink,continuedAttributes for h:message and h:messagesAttributetypevalueaccesskey, alt, binding, id, lang,rendered, styleClass, valuecoords (h:commandLink only), dir,disabled (h:commandButton only),hreflang (h:commandLink only),lang, readonly, rel (h:commandLinkonly), rev (h:commandLink only),shape (h:commandLink only), style,tabindex, target (h:commandLinkonly), title, typeonblur, onchange, onclick,ondblclick, onfocus, onkeydown,onkeypress, onkeyup, onmousedown,onmousemove, onmouseout,onmouseover, onmouseup, onselectDescriptionFor h:commandButton: The type ofthe generated input element: button,submit, or reset. The default, unless youspecify the image attribute, is submit. Forh:commandLink: The content type of thelinked resource; for example, text/html, image/gif, or audio/basicThe label displayed by the button or link.You can specify a string or a value referenceexpression.Basic attributesHTML 4.0DHTML eventsAttributeforerrorClasserrorStylefatalClassfatalStyleglobalOnlyinfoClassinfoStylelayoutshowDetailshowSummarytooltipDescriptionThe ID of the component whose message is displayed—applicableonly to h:messageCSS class applied to error messagesCSS style applied to error messagesCSS class applied to fatal messagesCSS style applied to fatal messagesInstruction to display only global messages—applicable only toh:messages. Default: falseCSS class applied to information messagesCSS style applied to information messagesSpecification for message layout: table or list—applicable onlyto h:messagesA boolean that determines whether message details are shown.Defaults are false for h:messages, true for h:messageA boolean that determines whether message summaries areshown. Defaults are true for h:messages, false for h:messageA boolean that determines whether message details are renderedin a tooltip; the tooltip is only rendered if showDetail andshowSummary are trueAttributes for h:outputLinkAttributeaccesskey, binding, converter, id,lang, rendered, styleClass, valuecharset, coords, dir, hreflang, lang,rel, rev, shape, style, tabindex,target, title, typeonblur, onchange, onclick, ondblclick,onfocus, onkeydown, onkeypress, onkeyup,onmousedown, onmousemove, onmouseout,onmouseover, onmouseupAttributedisabledClassenabledClasslayoutbinding, converter, id,immediate, styleClass,required, rendered,validator, value,valueChangeListeneraccesskey, border, dir,disabled, lang, readonly,style, size, tabindex,titleonblur, onchange, onclick,ondblclick, onfocus,onkeydown, onkeypress,onkeyup, onmousedown,onmousemove, onmouseout,onmouseover, onmouseup,onselectDescriptionCSS class for disabled elements—forh:selectOneRadio and h:selectManyCheckboxonlyCSS class for enabled elements—forh:selectOneRadio and h:selectManyCheckboxonlySpecification for how elements are laid out:lineDirection (horizontal) or pageDirection(vertical)—for h:selectOneRadio andh:selectManyCheckbox onlyBasic attributesHTML 4.0—border is applicable toh:selectOneRadio and h:selectManyCheckboxonly. size is applicable to h:selectOneListbox andh:selectManyListbox onlyDHTML eventsDescriptionBasic attributesHTML 4.0DHTML eventsAttributes for:h:selectBooleanCheckbox,h:selectManyCheckbox, h:selectOneRadio,h:selectOneListbox, h:selectManyListbox,h:selectOneMenu, h:selectManyMenuwarnClasswarnStylebinding, id,rendered,styleClassAttributebinding, id, rendered,styleClassCSS class for warning messagesCSS style for warning messagesBasic attributesstyle, title HTML 4.0Attributes for h:panelGridAttributebgcolorbordercellpaddingcellspacingcolumnClassescolumnsfooterClassframeheaderClassrowClassesrulessummarybinding, id, rendered,styleClass, valuedir, lang, style,title, widthonclick, ondblclick,onkeydown, onkeypress,onkeyup, onmousedown,onmousemove,onmouseout,onmouseover,onmouseupDescriptionBackground color for the tableWidth of the table’s borderPadding around table cellsSpacing between table cellsDescriptionBasic attributesstyle HTML 4.0Comma-separated list of CSS classes for columnsNumber of columns in the tableCSS class for the table footerSpecification for sides of the frame surrounding the tablethat are to be drawn; valid values: none, above, below,hsides, vsides, lhs, rhs, box, borderCSS class for the table headerComma-separated list of CSS classes for columnsSpecification for lines drawn between cells; valid values:groups, rows, columns, allSummary of the table’s purpose and structure used fornon-visual feedback such as speechBasic attributesHTML 4.0DHTML eventsAttributes for h:panelGroupDZone, Inc. |

tech facts at your fingertips7JavaServer FacesAttributes for h:dataTableAttributebgcolorbordercellpaddingcellspacingcolumnClassesfirstfooterClassframeheaderClassrowClassesrulessummaryDescriptionBackground color for the tableWidth of the table’s borderPadding around table cellsSpacing between table cellsComma-separated list of CSS classes for columnsIndex of the first row shown in the tableCSS class for the table footerFrame Specification for sides of the frame surrounding thetable that are to be drawn; valid values: none, above, below,hsides, vsides, lhs, rhs, box, borderCSS class for the table headerComma-separated list of CSS classes for rowsSpecification for lines drawn between cells; valid values:groups, rows, columns, allSummary of the table's purpose and structure used for nonvisualfeedback such as speechAttributes for h:dataTable, continuedAttributevarbinding, id, rendered,styleClass, valuedir, lang, style, title,widthonclick, ondblclick,onkeydown, onkeypress,onkeyup, onmousedown,onmousemove, onmouseout,onmouseover, onmouseupAttributes for h:columnAttributeheaderClass (JSF 1.2)footerClass (JSF 1.2)binding, id, renderedDescriptionThe name of the variable created by the data table thatrepresents the current item in the valueBasic attributesHTML 4.0DHTML eventsDescriptionCSS class for the column's headerCSS class for the column's footerBasic attributesA B O U T T H E A U T H O RCay S. HorstmannCay S. Horstmann has written many books on C++, Java and objectorienteddevelopment, is the series editor for Core Books at Prentice-Halland a frequent speaker at computer industry conferences. For four years,Cay was VP and CTO of an Internet startup that went from 3 people in atiny office to a public company. He is now a computer science professorat San Jose State University. He was elected Java Champion in 2005.List of recent books/publications• Core Java, with Gary Cornell, Sun Microsystems Press 1996 - 2007 (8 editions)• Core JavaServer Faces, with David Geary, Sun Microsystems Press, 2004-2006 (2 editions)• Big Java, John Wiley & Sons 2001 - 2007 (3 editions)Blog sitehttp://horstmann.comR E C O M M E N D E D B O O KCore JavaServer Facesdelves into all facets ofJSF development, offeringsystematic best practices forbuilding robust applicationsand maximizing developerproductivity.BUY More FREE Refcardz. Visit now!Upcoming Refcardz:Available:Core SeamCore CSS: Part IIIHibernate SearchEquinoxEMFXMLJSP Expression LanguageALM Best PracticesHTML and XHTMLEssential RubyEssential MySQLJUnit and EasyMockGetting Started with MyEclipseSpring AnnotationsCore JavaCore CSS: Part IIPHPGetting Started with JPAJavaServer FacesCore CSS: Part IStruts2Core .NETVery First Steps in FlexC#GroovyNetBeans IDE 6.1 Java EditorRSS and AtomGlassFish Application ServerSilverlight 2Visit for a complete listing of available Refcardz.FREEDesign PatternsPublished June 2008DZone communities deliver over 4 million pages each month tomore than 1.7 million software developers, architects and decisionmakers. DZone offers something for everyone, including news,tutorials, cheatsheets, blogs, feature articles, source code and more.“DZone is a developer’s dream,” says PC Magazine.DZone, Inc.1251 NW MaynardCary, NC 27513888.678.0399919.678.0300Refcardz Feedback Welcomerefcardz@dzone.comSponsorship Opportunitiessales@dzone.comCopyright © 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical,photocopying, or otherwise, without prior written permission of the publisher. Reference: Core JavaServer Faces, David Geary and Cay S. Horstmann, Sun Microsystems Press, 2004-2006.ISBN-13: 978-1-934238-19-6ISBN-10: 1-934238-19-85 0 7 9 59 781934 238196Version 1.0$7.95

More magazines by this user
Similar magazines