CONTENTS INCLUDE: JavaServer Faces

2y ago
30 Views
2 Downloads
2.35 MB
7 Pages
Last View : Today
Last Download : 3m ago
Upload by : Carlos Cepeda
Transcription

Brought to you by.#21Get More Refcardz! Visit refcardz.comtech facts at your fingertipsCONTENTS INCLUDE:nDevelopment ProcessnLifecyclenFaces-config.xmlnThe JSF Expression LanguagenJSF Core TagsnJSF HTML Tags and more.JavaServer FacesBy Cay S. HorstmannThese common tasks give you a crash course into using JSF.ABOUT THIS REFCARDText fieldJavaServer 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.page.jspx h:inputText value "#{bean1.luckyNumber}" faces-config.xml managed-bean managed-bean-name bean1 /managed-bean-name managed-bean-class com.corejsf.SampleBean /managed-bean-class managed-bean-scope session /managed-bean-scope /managed-bean T PROCESSpublic class SampleBean {public int getLuckyNumber() { . }public void setLuckyNumber(int value) { . }.}A 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.Buttonpage.jspx h:commandButton value "press me" action "#{bean1.login}"/ servlet containerclient devicesweb applicationpresentationJSF Pagesfaces-config.xmlapplication logicnavigationvalidationevent handlingbusiness logic navigation-rule navigation-case from-outcome success /from-outcome to-view-id /success.jspx /to-view-id /navigation-case navigation-case from-outcome error /from-outcome to-view-id /error.jspx /to-view-id redirect/ /navigation-case /navigation-rule databaseManaged BeansJSF frameworkwebserviceJavaServer FacesA JSF page has the following structure:JSP StyleProper XML html %@ taglib uri "http://java.sun.com/jsf/core"prefix "f" % %@ taglib uri "http://java.sun.com/jsf/html"prefix "h" % f:view head title . /title /head body h:form . /h:form /body /f:view /html ?xml version "1.0" encoding "UTF-8"? jsp:root xmlns:jsp "http://java.sun.com/JSP/Page"xmlns:f "http://java.sun.com/jsf/core"xmlns:h "http://java.sun.com/jsf/html" version "2.0" jsp:directive.page contentType "text/ html;charset UTF-8"/ jsp:output omit-xml-declaration "no"doctype-root-element "html"doctype-public "-//W3C//DTD XHTML 1.0 Transitional//EN"doctype-system "http://www.w3.org/TR/ xhtml1/DTD/xhtml1-transitional.dtd"/ f:view html xmlns "http://www.w3.org/1999/xhtml" head title . /title /head body h:form . /h:form /body /html /f:view /jsp:root DZone, Inc. www.dzone.com

2JavaServer Facestech facts at your fingertipsButton, continued. h:outputText value Class "goodbye" public class SampleBean { public String login() { if (.) return"success"; else return "error"; }.}. /body faces-config.xml application resource-bundle Radio buttonspage.jspx base-name com.corejsf.messages /base-name var msgs /var /resource-bundle h:selectOneRadio value "#{form.condiment} f:selectItems value "#{form.condimentItems}"/ /h:selectOneRadio /application ean.javagoodbye Goodbyecom/corejsf/messages de.propertiespublic class SampleBean { private Map String, Object condimentItem null;public Map String, Object getCondimentItems() {if (condimentItem null) { condimentItem new LinkedHashMap String,Object (); condimentItem.put("Cheese", 1); // label, valuecondimentItem.put("Pickle", 2);.}return condimentItem;}public int getCondiment() { . }public void setCondiment(int value) { . }.}goodbye Auf Wiedersehenstyles.css.goodbye {font-style: italic;font-size: 1.5em;color: #eee;}Table with linksNameValidation and ConversionWashington, GeorgeDeleteJefferson, ThomasDeleteLincoln, AbrahamDeleteRoosevelt, TheodoreDeletepage.jspxpage.jspx h:inputText value "#{payment.amount}" h:dataTable value "#{bean1.entries}" var "row"styleClass "table" rowClasses "even,odd" h:column f:facet name "header" h:outputText value "Name"/ /f:facet h:outputText value "#{row.name}"/ /h:column h:column h:commandLink value "Delete" action "#{bean1.deleteAction}" immediate "true" f:setPropertyActionListener target "#{bean1.idToDelete}"value "#{row.id}"/ /h:commandLink /h:column /h:dataTable required "true" f:validateDoubleRange maximum "1000"/ /h:inputText h:outputText value "#{payment.amount}" f:convertNumber type "currency"/ !-- number displayed with currency symbol andgroup separator: 1,000.00 -- /h:outputText Error Messagespage.jspx h:outputText value "Amount"/ h:inputText id "amount" label "Amount"value "#{payment.amount}"/ com/corejsf/SampleBean.java !-- label is used in message text -- public class SampleBean {private int idToDelete; public void setIdToDelete(int value) {idToDelete value; }public String deleteAction() { // delete the entry whose id is idToDeletereturn null;}public List Entry getEntries() {.}.} h:message for "amount"/ Resources and Stylespage.jspx head link href "styles.css" rel "stylesheet"type "text/css"/ . /head body DZone, Inc. www.dzone.com

3JavaServer Facestech facts at your fingertipsLIFECYCLEweb.xmlresponse completerequestRestoreViewApply RequestValuesProcessevents ?xml version "1.0"? web-app xmlns "http://java.sun.com/xml/ns/javaee"xmlns:xsi "http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app 2 5.xsd" version "2.5" servlet servlet-name Faces Servlet /servlet-name servlet-class javax.faces.webapp.FacesServlet /servlet-class load-on-startup 1 /load-on-startup /servlet response completeProcessValidationsProcesseventsrender responseresponse e aluesconversion errors/render responsevalidation or conversion errors/render response !-- Add this element to change the extension forJSF page files (Default: .jsp) -- context-param param-name javax.faces.DEFAULT SUFFIX /paramname faces-config.xmlThe faces-config.xml file contains a sequence of the followingentries.nmanaged-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 servlet-mapping welcome-file-list n /welcome-file-list /web-app THE 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.mOptional initialization (not shown here)mvalidator-idmvalidator-classmOptional initialization (not shown idm welcome-file index.html /welcome-file !-- Use meta http-equiv "Refresh" content "0; URL index.faces"/ -- converterm welcome-file index.faces /welcome-file !-- Create a blank index.faces (in addition toindex.jspx) -- applicationm url-pattern *.faces /url-pattern navigation-rule servlet-name Faces Servlet /servlet-name /servlet-mapping m 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 !-- Another popular URL pattern is /faces/* -- 1. description, display-name, icon (optional)2. from-view-id (optional, can use wildcards)3. navigation-case (1 or more)n from-action (optional, not common)n from-outcomen to-view-idn param-value .jspx /param-value /context-param phase-listener component, factory, referenced-bean, render-kit,faces-config-extension (details not shown)DZone, Inc. headerA Map of HTTP header parameters, containing only the firstvalue for each name.headerValuesA Map of HTTP header parameters, yielding a String[] array ofall values for a given name.paramA Map of HTTP request parameters, containing only the firstvalue for each name.paramValuesA Map of HTTP request parameters, yielding a String[] array ofall values for a given name.cookieA Map of the cookie names and values of the current request.initParamA Map of the initialization parameters of this web application.requestScopeA Map of all request scope attributes.sessionScopeA Map of all session scope attributes.applicationScopeA Map of all application scope attributes.facesContextThe FacesContext instance of this request.viewThe UIViewRoot instance of this request.www.dzone.com

4JavaServer Facestech facts at your fingertipsThe JSF Expression Language (EL), continuedJSF Core Tags, continuedThere are two expression types:n Value expression: a reference to a bean property or anentry in a map, list, or array. Examples:TagDescription/ Attributesf:convertNumberAdds a number converter to a component userBean.name calls getName or setName on the userBeanobject pizza.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:u serBean.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.typenumber (default), currency , orpercentpatternFormatting pattern, as defined injava.text.DecimalFormatmaxFractionDigitsMaximum number of digits in thefractional partminFractionDigitsMinimum number of digits in thefractional partmaxIntegerDigitsMaximum number of digits in theinteger partminIntegerDigitsMinimum number of digits in theinteger partintegerOnlyTrue if only the integer part isparsed (default: false)groupingUsedTrue if grouping separators areused (default: true)localeLocale whose preferences are tobe used for parsing and formattingcurrencyCodeISO 4217 currency code to usewhen converting currency valuescurrencySymbolCurrency symbol to use whenconverting currency valuesJSF CORE TAGSf:validatorAdds a validator to a componentThe ID of the validatorvalidatorIdTagDescription/ Attributesf:viewCreates the top-level viewf:subviewThe locale for this view.renderKitId(JSF 1.2)The render kit ID for this viewbeforePhase,afterPhasePhase listeners that are called inevery phase except "restore he name and value of the attribute to setConstructs a parameter child componentAn optional name for this parametercomponent.valueThe value stored in this component.binding, idBasic attributesAdds an action listener or value change listener to acomponentbasenameThe resource bundle namevalueThe name of the variable that is bound tothe bundle mapSpecifies items for a select one or select many componentbinding, idBasic attributesvalueValue 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, idBasic attributesitemDescriptionDescription used by tools onlyitemDisabledBoolean value that sets the item’sdisabled propertyitemLabelText shown by the itemitemValueItem’s value, which is passed to theserver as a request parametervalueValue expression that points to aSelectItem instanceThe name of the listener classf:verbatimAdds an action listener to a component that sets a beanproperty to a given value.valueThe bean property to set when theaction event occursbinding, idThe value to set it toAdds an arbitary converter to a Basic attributesthe minimum and maximum of thevalid rangLoads a resource bundle, stores properties as a MapAdds an attribute to a componenttypef:setPropertyChangeListener (JSF 1.2)minimum, maximumthe name of this facetnamef:actionListenerf:loadBundleAdds a facet to a componentname, valuef:paramValidates a double or long value, or the length of a stringf:validateLengthCreates a subview of a g, id, renderedf:facetf:validateDoubleRangeAdds markup to a JSF pageescapeIf set to true, escapes , , and &characters. Default value is false.rendered (JSF 1.2)Basic attributesJSF HTML TAGSThe ID of the converterAdds a datetime converter to a componentTagDescriptiontypedate (default), time, or bothh:formHTML formdateStyledefault, short, medium, long, or fullh:inputTextSingle-line text input controltimeStyledefault, short, medium, long, or fullh:inputTextareaMultiline text input controlpatternFormatting pattern, as defined in java.text.SimpleDateFormatlocaleLocale whose preferences are to be usedfor parsing and formattingh:inputSecretPassword input controltimezoneTime zone to use for parsing andformattingh:inputHiddenHidden fieldh:outputLabelLabel for anothercomponent for accessibility DZone, Inc. www.dzone.com

5JavaServer Facestech facts at your fingertipsAttributes for h:inputText ,h:inputSecret, h:inputTextarea ,and h:inputHiddenJSF HTML tags, continuedTagDescriptionh:outputLinkHTML anchorLike outputText, butformats ine text outputh:commandButtonButton: submit, reset, orpushbuttonh:commandLinkLink that acts like apushbutton.registerDisplays the most recentmessage for a componentAmounth:messagetoo muchAmount:'too much' is not anumber.Example: 99AttributeDescriptioncolsFor h:inputTextarea only—number of columnsimmediateProcess validation early in the life cycleredisplayFor h:inputSecret only—when true, the inputfield’s value is redisplayed when the web page isreloadedrequiredRequire input in the component when the form issubmittedrowsFor h:inputTextarea only—number of rowsvalueChangeListenerA specified listener that’s notified of value changesbinding, converter, id, rendered,required, styleClass, value,validatorBasic attributesh:messagesDisplays all messagesaccesskey, alt, dir,disabled, lang, maxlength,readonly, size, style,tabindex, titleHTML 4.0 pass-through attributes—alt, maxlength,and size do not apply to h:inputTextarea. Noneapply to h:inputHiddenh:grapicImageDisplays an imageDHTML events. None apply to h:inputHiddenh:selectOneListboxSingle-select listboxonblur, onchange, onclick,ondblclick, onfocus,onkeydown, onkeypress,onkeyup, onmousedown,onmousemove, onmouseout,onmouseover, onselecth:selectOneMenuSingle-select menuAttributes for h:outputText dioSet of radio buttonsescapeIf set to true, escapes , , and &characters. Default value is true.h:selectBooleanCheckboxCheckboxMultiselect listboxbinding, converter, id, rendered,styleClass, valueBasic at tributesh:selectManyCheckboxstyle, titleHTML 4.0h:selectManyListboxMultiselect listboxAttributes for ultiselect menuforThe ID of the component to be labeled.h:panelGridHTML tableBasic attributesh:panelGroupTwo or more componentsthat are laid out as onebinding, converter, id, rendered,valueh:dataTableA feature-rich tablecomponenth:columnColumn in a data tableAttributes for h:graphicImageBasic AttributesAttributeDescriptionidIdentifier for a componentbindingReference to the component that can be used in a backingbeanrenderedA boolean; false suppresses renderingstyleClassCascading stylesheet (CSS) class namevalueA component’s value, typically a value bindingvalueChangeListenerA method binding to a method that responds to valuechangesconverterConverter class namevalidatorClass name of a validator that’s created and attached to acomponentrequiredA boolean; if true, requires a value to be entered in theassociated fieldDescriptionbinding, id, rendered, styleClassBasic attributesaccept, acceptcharset, dir, enctype, lang,style, target, titleHTML 4.0 attributes(acceptcharset corresponds toHTML accept-charset)onblur, onchange, onclick, ondblclick, onfocus, DHTML eventsonkeydown, onkeypress, onkeyup, onmousedown,onmousemove, onmouseout, onmouseover, onreset,onsubmitDZone, Inc.Descriptionbinding, id, rendered, styleClass, valueBasic attributesalt, dir, height, ismap, lang, longdesc, style,title, url, usemap, widthHTML 4.0onblur, onchange, onclick, ondblclick, onfocus,onkeydown, onkeypress, onkeyup, onmousedown,onmousemove, onmouseout, onmouseover,onmouseupDHTML eventsAttributes for h:commandButtonand h:commandLinkAttributes for h:formAttributeAttribute AttributeDescriptionactionIf 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 outcomeactionListenerA method binding that refers to a method withthis signature: void methodName(ActionEvent)charsetFor h:commandLink only—The characterencoding of the linked referenceimageFor h:commandButton only—A context-relativepath to an image displayed in a button. If youspecify this attribute, the HTML input’s type willbe image.immediateA 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.www.dzone.com

6JavaServer Facestech facts at your fingertipsh:commandButton and h:commandLink ,Attributes for h:message and h:messagescontinuedAttributeDescriptiontypeFor 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.valueaccesskey, alt, binding, id, lang,rendered, styleClass, valueBasic attributescoords (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, typeHTML 4.0onblur, onchange, onclick,ondblclick, onfocus, onkeydown,onkeypress, onkeyup, onmousedown,onmousemove, onmouseout,onmouseover, onmouseup, onselectDHTML eventsAttributes for h:outputLinkAttributeDescriptionaccesskey, binding, converter, id,lang, rendered, styleClass, valueBasic attributescharset, coords, dir, hreflang, lang,rel, rev, shape, style, tabindex,target, title, typeHTML 4.0onblur, onchange, onclick, ondblclick,onfocus, onkeydown, onkeypress, onkeyup,onmousedown, onmousemove, onmouseout,onmouseover, onmouseupDHTML eventsAttributeDescriptionforThe ID of the component whose message is displayed—applicableonly to h:messageerrorClassCSS class applied to error messageserrorStyleCSS style applied to error messagesfatalClassCSS class applied to fatal messagesfatalStyleCSS style applied to fatal messagesglobalOnlyInstruction to display only global messages—applicable only toh:messages. Default: falseinfoClassCSS class applied to information messagesinfoStyleCSS style applied to information messageslayoutSpecification for message layout: table or list—applicable onlyto h:messagesshowDetailA boolean that determines whether message details are shown.Defaults are false for h:messages, true for h:mess

JSF includes a set of predefined UI components, an event-driven programming model, and the ability to add third-party components. JSF is designed to be extensible, easy to use, and toolable. This refcard describes the JSF development process, standard JSF tags, the JSF expressi

Related Documents:

Building JavaServer Faces Applications 7 JSF – A Web Framework JSR 127 – JSF specification v1.1 JSF 1.2 in progress (JSR 252) JSP 2.1 (JSR 245) will align with JSF JSF spec lead was the Struts architect JavaServer Faces technology simplifies building user interfaces for JavaServer

JavaServer Faces (JSF) is a relatively new user interface technology, having been added to the Java standard with Java EE 5. It is supported in the AS Java 7.1 since it supports Java EE 5. In addition the SAP NetWeaver Developer Studio (NWDS) is based on Eclipse 3.3 which in turn comes w

Faces: j 5. Faces: 8 6. Faces: 20 Edges: 15 Edges: j Edges: 30 Vertices: 9 Vertices: 6 Vertices: j Use Euler’s Formula to find the number of vertices in each polyhedron described below. 7. 6 square faces 8. 5 faces: 1 rectangle 9. 9 faces: 1 octagon and 4 triangles and 8 triangles Verify Euler’s Formula for each polyhedron.Then draw a net .

IMS IBM Information Management System (mainframe hierarchical database) IMS Information Management System IP Internet Protocol IVR Interactive Voice Response J2EE Java 2 Platform, Enterprise Edition JAM Java Adapter for Mainframe JCL Job Control Language JDBC Java Database Connectivity JSF JavaServer Faces JSP JavaServer Pages Mass

Title: WA1618 Introduction to JavaServer Faces (JSF) 1.2 Using

6 faces 5 faces 12 edges 9 edges 8 corners 6 corners c prism d pyramid 6 faces 5 faces 12 edges 8 edges 8 corners 5 corners 2 Draw two 3D objects that have no corners. faces sphere cylinder. 92 Shape ISBN: 978-0-521-74532-1 Photocopying is restricted under law and this material must not be transferred to another party.

Faces, Edges, and Vertices Practice Circle the shapes or objects that matches the description. 1. 6 faces, 12 edges, 8 vertices 2. 0 faces, 0 edges, 0 vertices 3. 5 fac es, 8 edges, 5 vertices 4. 6 faces, 12 edges, 8 vertices Three-dimensional shapes are described by the number of faces, edges, and vertices. A face is a flat surface.

JavaServer Pages J avaServer Pages (JSP) and Servlets are complementary technologies for pro-ducing dynamic Web pages via Java.While Servlets are the foundation for server-side Java, they are not always the most efficient solution with respect to development time. Coding, deploying, and debugging a Servlet can be a tedious task.