Your SlideShare is downloading. ×

JSF2 Tutorial: Composite Components Part 2 -- Input Components

4,065
views

Published on

This is the second of four sections on using the new composite component approach to dramatically simplify custom components (as compared to the JSF 1 API). Along with Ajax and perhaps page …

This is the second of four sections on using the new composite component approach to dramatically simplify custom components (as compared to the JSF 1 API). Along with Ajax and perhaps page templating, this is the most important features of JSF 2. See http://www.coreservlets.com/JSF-Tutorial/jsf2/ for the complete tutorial series, associated code, exercises, and exercise solutions. You can also download PDF files of each lecture, for saving or printing. That site also lets you download PDF files of each lecture, for saving or printing. Please email hall@coreservlets.com for info on how to arrange customized courses on JSF 2.2, PrimeFaces, Java 8, and other Java EE topics onsite at YOUR location.

Published in: Technology, Education

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
4,065
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
2
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • 3
  • Transcript

    • 1. © 2014 Marty Hall JSF 2 Composite Components Part II – Input Components JSF 2.2 Version Originals of slides and source code for examples: http://www.coreservlets.com/JSF-Tutorial/jsf2/ Also see the PrimeFaces tutorial – http://www.coreservlets.com/JSF-Tutorial/primefaces/ and customized JSF2 and PrimeFaces training courses – http://courses.coreservlets.com/jsf-training.html Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
    • 2. © 2014 Marty Hall For live training on JSF 2 and/or PrimeFaces, email hall@coreservlets.com. Marty is also available for consulting and development support. Taught by the author of Core Servlets and JSP, this tutorial, and JSF 2.2 version of Core JSF. Available at public venues, or customized versions can be held on-site at your organization. • Courses developed and taught by Marty Hall – JSF 2.2, PrimeFaces, servlets/JSP, Ajax, jQuery, Android development, Java 7 or 8 programming, custom mix of topics – Courses available in any state or country. Maryland/DC area companies can also choose afternoon/evening courses. Customized Java EE Training: http://courses.coreservlets.com/ • Courses developed and taught by coreservlets.com experts (edited by Marty) Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. – Hadoop, Spring, Hibernate/JPA, GWT, RESTful Web Services Developed and taught by well-known author and developer. At public venues or onsite at your location. Contact hall@coreservlets.com for details
    • 3. Topics in This Section • Idea • Making basic input components • Using the “type” attribute • Giving components their own CSS file 5
    • 4. © 2014 Marty Hall Overview: Input Components Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
    • 5. Input Components • Idea – A composite component that will go inside h:form and be used to gather input from the user • Features – Must be associated with a bean value • Use “type” attribute to enforce the type of the value – Often has its own style sheet • Load with h:outputStylesheet – May need to assemble final value out of submitted pieces – May need to call component setter methods based on attribute values – May have embedded Ajax behavior – May be built out of a rich JavaScript GUI element 7
    • 6. © 2014 Marty Hall Basic Input Components Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
    • 7. Input Components: Basic Steps • Use JSF input element(s) in cc:implementation – E.g., h:inputText, h:selectOneMenu, etc. • Do not include h:form – Otherwise your component cannot be combined with other input components in a single form • In most cases, name the main attribute “value” – To be consistent with standard input elements – Similarly, mimic other standard attribute names (styleClass, required, etc.) • Use the “type” attribute of cc:attribute to hook the element(s) to bean properties. Use fully qualified name. – <cc:attribute name="value" required="true" type="coreservlets.Nameable"/> • Except for builtin types, have “type” refer to an interface – For flexibility, so component can be used in many places 9
    • 8. Example: inputName1 • Idea – Collect a first and last name • Code summary – Use two h:inputText elements – Make a Nameable interface that defines getFirstName, setFirstName, getLastName, and setLastName (i.e., firstName and lastName bean properties). Have “type” refer to coreservlets.Nameable – Add optional properties with defaults to specify the prompts in front of the two textfields 10
    • 9. Nameable Interface package coreservlets; public interface Nameable { public String getFirstName(); public void setFirstName(String firstName); public String getLastName(); public void setLastName(String lastName); } 11
    • 10. Component Outline • Filename: inputName1.xhtml – In WebContent/resources/utils • Basic code <!DOCTYPE html ...> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:cc="http://xmlns.jcp.org/jsf/composite"> <cc:interface> Declare value, firstNamePrompt, lastNamePrompt, required, requiredMessage </cc:interface> <cc:implementation> Make two input fields, one for first name, one for last name. </cc:implementation> </html> 12
    • 11. Component: Interface Section <cc:interface> <cc:attribute name="value" required="true" type="coreservlets.Nameable"/> <cc:attribute name="firstNamePrompt" required="false" default="First Name"/> <cc:attribute name="lastNamePrompt" required="false" default="Last Name"/> <cc:attribute name="required" required="false" default="true"/> <cc:attribute name="requiredMessage" required="false" default="Required!"/> </cc:interface> 13
    • 12. Component: Implementation Section <cc:implementation> <h:panelGrid columns="3"> #{cc.attrs.firstNamePrompt}: <h:inputText value="#{cc.attrs.value.firstName}" id="firstName" required="#{cc.attrs.required}" requiredMessage="#{cc.attrs.requiredMessage}"/> <h:message for="firstName" style="font-weight: bold; color: red"/> #{cc.attrs.lastNamePrompt}: <h:inputText value="#{cc.attrs.value.lastName}" id="lastName" required="#{cc.attrs.required}" requiredMessage="#{cc.attrs.requiredMessage}"/> <h:message for="lastName" style="font-weight: bold; color: red"/> </h:panelGrid> 14 </cc:implementation>
    • 13. Example Usage 1: Employee of Month • Idea – Nominate employee of the month for the corporation • Managed Bean – Implements Nameable – Also stores a nomination reason • Page that uses component – Collects name and nomination reason • Results page – Shows confirmation with first name, last name, and nomination reason 15
    • 14. Managed Bean (First Half) @ManagedBean public class EmployeeOfMonth implements Nameable { private String firstName, lastName; private String nominationReason; public String getFirstName() { return(firstName); } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return(lastName); } public void setLastName(String lastName) { this.lastName = lastName; } 16
    • 15. Managed Bean (Second Half) public String getNominationReason() { return(nominationReason); } public void setNominationReason(String nominationReason) { this.nominationReason = nominationReason; } public String recordVote() { storeVoteSomehow(); return("show-employee-vote"); } private void storeVoteSomehow() { // Nothing to see here. Move along. } } 17
    • 16. Facelets Page that Uses Component ... <fieldset> <legend>Employee of the Month</legend> <h2>Nominate this Month's Top Employee!</h2> <h:form> <utils:inputName1 value="#{employeeOfMonth}"/> Reason: <h:inputText value="#{employeeOfMonth.nominationReason}" size="75"/><br/> <h:commandButton action="#{employeeOfMonth.recordVote}" value="Record Vote"/> </h:form> </fieldset> ... 18
    • 17. Results Page ... <fieldset> <legend>Employee of Month</legend> <ul> <li>Name: #{employeeOfMonth.firstName} #{employeeOfMonth.lastName} </li> <li>Reason: #{employeeOfMonth.nominationReason}</li> </ul> </fieldset> ... 19
    • 18. Result: Page that Uses Component 20 Original (blank) form After submitting with missing first/last names
    • 19. Result: Results Page 21
    • 20. Usage 2: Write-in Ballot for US General Election (Maryland) • Idea – Lets voters enter a name for president and vice president, and also vote on two local (state) initiatives. • Managed Bean – Parent class: uses Person, which implements Nameable, has getters/setters for the two state propositions, has getters for the descriptions of the propositions – Subclass: provides descriptions of the propositions, has action controller method the verifies that president and vice president are different people • Page that uses component – Collects president’s name, vice president’s name, and yes/no votes on the two propositions • Results page – Shows confirmation for president, VP, and propositions 22
    • 21. Parent Class of Managed Bean (Beginning) public class WriteinBallot { private final Person president, vicePresident; private boolean forProp1, forProp2; private final String prop1Description, prop2Description; public WriteinBallot(String prop1Description, String prop2Description) { this.prop1Description = prop1Description; this.prop2Description = prop2Description; forProp1 = true; forProp2 = true; president = new Person(); vicePresident = new Person(); } 23
    • 22. Parent Class of Managed Bean (Continued) public Person getPresident() { return (president); } public Person getVicePresident() { return (vicePresident); } public boolean isForProp1() { return (forProp1); } public void setForProp1(boolean forProp1) { this.forProp1 = forProp1; } public String getProp1Description() { return (prop1Description); 24 }
    • 23. Parent Class of Managed Bean (Continued) public boolean isForProp2() { return (forProp2); } public void setForProp2(boolean forProp2) { this.forProp2 = forProp2; } public String getProp2Description() { return (prop2Description); } } 25
    • 24. Person (Used by Parent Class) public class Person implements Nameable { private String firstName="", lastName=""; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public Person() {} 26
    • 25. Person (Continued) public String getFirstName() { return(firstName); } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return(lastName); } public void setLastName(String lastName) { this.lastName = lastName; } public String getFullName() { return(firstName + " " + lastName); } } 27
    • 26. Managed Bean (First Half) @ManagedBean public class MarylandBallot extends WriteinBallot { public MarylandBallot() { super("To require all Maryland elementary schools " + "to teach Java programming", "To have Java programming replace lacrosse " + "as the official state team sport"); } 28
    • 27. Managed Bean (Second Half) public String checkBallot() { Person pres = getPresident(); Person vp = getVicePresident(); if (pres.getFirstName().equals(vp.getFirstName()) && pres.getLastName().equals(vp.getLastName())) { FacesContext context = FacesContext.getCurrentInstance(); FacesMessage errorMessage = new FacesMessage("Cannot vote for same person for " + "President and Vice President"); context.addMessage(null, errorMessage); return(null); } else { return("show-ballot-vote"); } } } 29
    • 28. Facelets Page that Uses Component ... <h:form> <b>President</b><br/> <utils:inputName1 value="#{marylandBallot.president}"/><br/> <b>Vice President:</b><br/> <utils:inputName1 value="#{marylandBallot.vicePresident}"/><br/> <b>#{marylandBallot.prop1Description}</b> <h:selectOneRadio value="#{marylandBallot.forProp1}"> <f:selectItem itemValue="true" itemLabel="For"/> <f:selectItem itemValue="false" itemLabel="Against"/> </h:selectOneRadio> <b>#{marylandBallot.prop2Description}</b> <h:selectOneRadio value="#{marylandBallot.forProp2}"> <f:selectItem itemValue="true" itemLabel="For"/> <f:selectItem itemValue="false" itemLabel="Against"/> </h:selectOneRadio> <br/> <h:commandButton action="#{marylandBallot.checkBallot}" value="Submit Vote"/> 30 </h:form>...
    • 29. Results Page ... <fieldset> <legend>Maryland Write-in Ballot</legend> <ul> <li>President: #{marylandBallot.president.fullName}</li> <li>Vice President: #{marylandBallot.vicePresident.fullName}</li> <li>Voted for Proposition 1 (#{marylandBallot.prop1Description}): #{marylandBallot.forProp1}</li> <li>Voted for Proposition 2 (#{marylandBallot.prop2Description}): #{marylandBallot.forProp2}</li> </ul> </fieldset> 31 ...
    • 30. Result: Page that Uses Component 32 Original (blank) form After submitting with missing first/last names
    • 31. Result: Results Page 33
    • 32. © 2014 Marty Hall Giving Stylesheets to Components Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
    • 33. Overview • Motivation – CSS-based alignment is often needed by components that consist of multiple pieces • E.g., for name component, make table cell that holds the prompts be right-aligned, and table cell that holds the textfields be left-aligned – Fonts and colors should be overridable by page author • Basic steps – Create a “css” (or similar) subfolder within your component folder (which, in turn, is inside “resources”) – Put style sheet in that folder – Load the style sheet with <h:outputStylesheet name="stylesheet-name.css" library="component-folder/css"/> • Even though this is not in “head” section of original file, the HTML tag to load style sheet will be in head of rendered page 35
    • 34. Component Outline • Filename: inputName2.xhtml – In WebContent/resources/utils • Basic code <!DOCTYPE html ...> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:cc="http://xmlns.jcp.org/jsf/composite"> <cc:interface> Declare value, firstNamePrompt, lastNamePrompt, required, requiredMessage, errorStyleClass </cc:interface> <cc:implementation> Make two input fields, one for first name, one for last name. Align with CSS. CSS for errors. </cc:implementation> </html> 36
    • 35. Component: Interface Section <cc:interface> <cc:attribute name="value" required="true" type="coreservlets.Nameable"/> <cc:attribute name="firstNamePrompt" required="false" default="First Name"/> <cc:attribute name="lastNamePrompt" required="false" default="Last Name"/> <cc:attribute name="required" required="false" default="true"/> <cc:attribute name="requiredMessage" required="false" default="Required!"/> <cc:attribute name="errorStyleClass" required="false" default="name-error"/> </cc:interface> 37
    • 36. Component: Implementation Section (First Half) <cc:implementation> <h:outputStylesheet name="utils-styles.css" library="utils/css"/> <h:panelGrid columns="3" styleClass="formTable"> #{cc.attrs.firstNamePrompt}: <h:inputText value="#{cc.attrs.value.firstName}" id="firstName" required="#{cc.attrs.required}" requiredMessage="#{cc.attrs.requiredMessage}"/> <h:message for="firstName" styleClass="#{cc.attrs.errorStyleClass}"/> 38
    • 37. Component: Implementation Section (Second Half) #{cc.attrs.lastNamePrompt}: <h:inputText value="#{cc.attrs.value.lastName}" id="lastName" required="#{cc.attrs.required}" requiredMessage="#{cc.attrs.requiredMessage}"/> <h:message for="lastName" styleClass="#{cc.attrs.errorStyleClass}"/> </h:panelGrid></cc:implementation> 39
    • 38. Examples: Employee of Month and Maryland Ballot • CSS – R-aligns the prompts – Makes error messages bold and red by default, but can be overridden by passing in errorStyleClass • Managed beans – Reused from previous examples without changes • Page that uses component – Mostly same as previous examples, but optionally supplies an errorStyleClass • Results pages – Reused from previous examples without changes 40
    • 39. Employee of Month: Facelets Page that Uses Component ... <h2>Nominate this Month's Top Employee!</h2> <h:form> <utils:inputName2 value="#{employeeOfMonth}"/> Reason: <h:inputText value="#{employeeOfMonth.nominationReason}" size="75"/><br/> <h:commandButton action="#{employeeOfMonth.recordVote}" value="Record Vote"/> </h:form> ... 41
    • 40. Result: Employee of Month (Input Form) 42 Original (blank) form. Same as previous except for prompt alignment. After submitting with missing first/last names
    • 41. Result: Employee of Month (Results Page) 43
    • 42. Write-in Ballot: Facelets Page that Uses Component (1st Half) ... <h:form> <b>President</b><br/> <utils:inputName2 value="#{marylandBallot.president}" firstNamePrompt="First (Given) Name" lastNamePrompt="Last (Family) Name" errorStyleClass="blue-error"/><br/> <b>Vice President:</b><br/> <utils:inputName2 value="#{marylandBallot.vicePresident}" firstNamePrompt="First (Given) Name" lastNamePrompt="Last (Family) Name" errorStyleClass="blue-error"/><br/> 44
    • 43. Write-in Ballot: Facelets Page that Uses Component (2nd Half) <b>#{marylandBallot.prop1Description}</b> <h:selectOneRadio value="#{marylandBallot.forProp1}"> <f:selectItem itemValue="true" itemLabel="For"/> <f:selectItem itemValue="false" itemLabel="Against"/> </h:selectOneRadio> <b>#{marylandBallot.prop2Description}</b> <h:selectOneRadio value="#{marylandBallot.forProp2}"> <f:selectItem itemValue="true" itemLabel="For"/> <f:selectItem itemValue="false" itemLabel="Against"/> </h:selectOneRadio> <br/> <h:commandButton action="#{marylandBallot.checkBallot}" value="Submit Vote"/> </h:form> ... 45
    • 44. Result: Write-in Ballot (Input Form) 46 Original (blank) form. Same as previous except for prompt alignment. After submitting with missing first/last names. Same as previous except for style of error messages.
    • 45. Result: Write-in Ballot (Results Page) 47
    • 46. © 2014 Marty Hall Wrap-Up Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
    • 47. Summary • Associate input element with bean value – Use “type” attribute to enforce the type of the value – Except for builtin types, use interface, not class, for the value • Use style sheets – Load with h:outputStylesheet – Often used for alignment – For fonts and colors, let page author override your styles 49
    • 48. © 2014 Marty Hall Questions? More info: http://www.coreservlets.com/JSF-Tutorial/jsf2/ – JSF 2.2 tutorial http://www.coreservlets.com/JSF-Tutorial/primefaces/ – PrimeFaces tutorial http://courses.coreservlets.com/jsf-training.html – Customized JSF and PrimeFaces training courses http://coreservlets.com/ – JSF 2, PrimeFaces, Java 7 or 8, Ajax, jQuery, Hadoop, RESTful Web Services, Android, HTML5, Spring, Hibernate, Servlets, JSP, GWT, and other Java EE training Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.