You are on page 1of 30

© 2011 Marty Hall

JSF 2 0: Managed Beans – 2.0: Classes to Represent Form Info
Originals of Slides and Source Code for Examples:
Customized Java EE Training:
Servlets, JSP, JSF 2.0, Java 6, Ajax, jQuery, GWT, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2011 Marty Hall

For live training on JSF 2.0, please see courses at htt // t l t /
Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial. Available at public JSP, tutorial venues, or customized versions can be held on-site at your organization.
•C Courses d developed and t l d d taught b M t H ll ht by Marty Hall • Courses developed and taught by experts (edited by Marty)
– JSF, servlets/JSP, Ajax, jQuery, Android development, Java 6 programming, custom mix of topics – Ajax courses can concentrate on 1EE Training: Customized Java library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, etc.) or survey

Servlets, JSP, Hibernate/JPA, EJB3, GWT, jQuery, GWT, RESTful Web Services RESTful Web Services, Android. – Spring, JSF 2.0, Java 6, Ajax, SOAP-based and Spring, Hibernate, Contact for details Developed and taught by well-known author and developer. At public venues or onsite at your location.

Topics in This Section
• • • • • Basic beans and “managed” beans Three parts of beans in JSF Prepopulating input fields Accessing the request & response objects Review of bean scopes


© 2011 Marty Hall

Basic Beans and g “Managed” Beans
Customized Java EE Training:
Servlets, JSP, JSF 2.0, Java 6, Ajax, jQuery, GWT, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Background: Basic Beans
• Java classes that follow certain conventions
– Must have a zero-argument (empty) constructor
• You can satisfy this requirement either by explicitly defining such a constructor or by omitting all constructors g y g

– Should have no public instance variables (fields)
• You should already follow this practice and use accessor methods instead of allowing direct access to fields

– Persistent values should be accessed through methods called getBlah and setBlah
• If class has method getTitle that returns a String, class is said to have a String property named title
– JSF uses #{book.title} to mean “call getTitle on ‘book’ ”.

• Boolean properties may use isBlah instead of getBlah • What matters is method name, not instance variable name

More on Bean Properties
• Usual rule to turn method into property
– D Drop th word “get” or “set” and change the next letter to the d “ t” “ t” d h th t l tt t lowercase. Again, instance var name is irrelevant.
• Method name: getFirstName • Property name: firstName • Example: #{customer.firstName}

• Exception 1: boolean properties
– If getter returns boolean or Boolean b l B l
• Method name: getPrime or isPrime • Property name: prime • Example: #{myNumber prime} #{}

• Exception 2: consecutive uppercase letters
– If two uppercase letters in a row after “get” or “set”
• Method name: getURL • Property name: URL (not uRL) • Example: #{webSite.URL}


• OOP design 10 – You should do this in all your Java code anyhow.speed = speed. after you create instance variable. you should not have public fields.ZIP} <h:inputText value="#{address. Note 2: property name is derived only from method name. // Var need not match method name public double getSpeed() { return(speed). It is just a shortcut for the method name.firstName}"/> #{customer. Accessors Not Public Fields • Bean rules – T be a bean.executive} /> value="#{customer executive}"/> #{customer.executive} <h:selectBooleanCheckbox value= #{customer. Why? .firstName} <h:inputText value="#{customer.executive} /> value="#{customer executive}"/> #{address. – Right private double speed. Instance variable name is irrelevant. generate getters and setters for you. Note: in Eclipse.Bean Properties: Examples Method Names N getFirstName setFirstName isExecutive setExecutive (boolean property) getExecutive setExecutive (boolean property) getZIP setZIP Property Name N firstName Example JSF U Usage #{customer.ZIP}"/> executive executive ZIP Note 1: property name does not exist anywhere in your code. it gives you option to R click Source .executive} <h:selectBooleanCheckbox value= #{customer. To b b h ld h bli fi ld – Wrong public double speed. if } you R-click and choose “Source”. } public void setSpeed(double speed) { this. 9 Why You Should Use Accessors.

p ) public void setSpeed(double newSpeed) { speedInKPH = convert(newSpeed). } public oid setSpeedInKPH(double newSpeed) p blic void setSpeedInKPH(do ble ne Speed) { speedInKPH = newSpeed. not mph) g (kph.). } 12 .Why You Should Use Accessors. then they would each be responsible for checking constraints.. 11 Why You Should Use Accessors. newSpeed = Math.abs(newSpeed). } speed = newSpeed. Accessors Not Public Fields • 1) You can put constraints on values public void setSpeed(double newSpeed) { if (newSpeed < 0) { sendErrorMessage(. } – If users of your class accessed the fields directly. Accessors Not Public Fields • 2) You can change your internal representation without changing interface i ih h i i f // Now using metric units ( p ..

then they would each be responsible for executing side effects. } – If users of your class accessed the fields directly. Too much work and runs huge risk of having display inconsistent from actual values.HTMLString} 14 .firstName} • isVeryCool method (boolean): refer to “veryCool” – #{invention veryCool} #{invention. Accessors Not Public Fields • 3) You can perform arbitrary side effects public double setSpeed(double newSpeed) { speed = newSpeed.veryCool} • getHTMLString method: refer to “HTMLString” – #{message. updateSpeedometerDisplay(). 13 Basic Beans: Bottom Line • It is no onerous requirement to be a “bean” – You are probably following most of the conventions already anyhow • Zero arg constructor • No public instance variables • Use getBlah/setBlah or isBlah/setBlah naming conventions • JSF often refers to “bean properties” ft f t “b ti ” – Which are shortcuts for getter/setter methods • getFirstName method: refer to “firstName” firstName – #{customer.Why You Should Use Accessors.

GWT. JSF 2. Spring. Ajax.. At public venues or onsite at your location.xml © 2011 Marty Hall The Three Parts of g Managed Beans Customized Java EE Training: http://courses.coreservlets. session. RESTful Web Servlets. JSP. Android.firstName"/>.0. f <h:inputText value="#{customer. for #{ f / when form submitted.Managed Beans • JSF automatically “manages” the bean – Instantiates it • Thus the need for a zero-arg constructor – Controls its lifecycle • Scope (request.xml 15 • See separate section on navigation and faces-config.firstName} results in calling getFirstName • Declaring beans – Si l t @ManagedBean before class Simplest: @M dB b f l – Most powerful: <managed-bean> in faces-config. the value is passed to setFirstName – Calls getter methods • #{customer. Java 6. . jQuery. application) determines lifetime – Calls setter methods • I. Hibernate. Developed and taught by well-known author and developer.

.e. where customerId was passed in by the user.xhtml Uses <h:commandButton … action="#{bankForm.customerId}. or it could be #{bankForm. But for other scopes (e.xhtml Uses #{ #{bankForm. Run Setter Methods submit form POST request b l t balance. resultN.customer. but could be several if the same form has one multiple push buttons • Action controller method (corresponding to the button that was pressed) called automatically by JSF – Placeholders for results data • Not automatically called by JSF: to be filled in by action controller method b t ll th d based on results of b i d lt f business l i logic.. instantiate it. 18 .g.findBalance}"/> and <h:inputText value="#{bankForm.someProperty} p y} to display bean properties This could be #{bankForm...jsf j f Business Logic results The results get stored in the placeholder. pairs of getter and setter methods) • One pair for each input element • Setter methods called automatically by JSF when form submitted – Action controller methods • Often only one. session).balance}.xhtml result2. it becomes initial value of the textfield. and getBalance returns that customer’s bank account balance. When form first displayed.Overview • Managed beans typically have three parts – Bean properties (i. where getCustomer returns the Customer object found by the business logic.. getCustomerId is called. This is the method listed in the action of h:commandButton (e.g.g. If it is non-empty.customerId}"/> When form submitted. findBalance) result1. 17 JSF Flow of Control (Simplified) balance. Find Bean Run Action Controller Method return value l Choose Page forward If bean is request-scoped. textfield value passed to setCustomerId. a Customer that corresponds to the customer ID is found and placed in an instance variable of main bean.xhtml . E. you might use existing bean instance.

… <fieldset> <legend>Enter Your Customer ID</legend> <p>Legal ids are id001. getCustomerId and setCustomerId – Action controller method • Maps a customer ID to a Customer and stores the Customer in an instance variable – Placeholder for results data l h ld f l d 19 • An initially empty instance variable (for storing the Customer) and associated getter method. id002.w3. submitted. the textfield is initially empty When the form is submitted textfield Otherwise empty. and" xmlns http://www.customerId}"/><br/> <h:commandButton value="Show Current Balance" action="#{bankForm.Example • Idea – Enter a bank customer ID – Get either • Page showing first name last name and balance name.w3.xhtml) (customer-lookup xhtml) <!DOCTYPE …> <html xmlns=""> … This value plays a dual role.e. non-empty that result is the initial value of the textfield. If the value is <h:body> non empty.</p> / <h:form> Customer ID: <h:inputText value="#{bankForm customerId}"/><br/> value="#{bankForm. BankForm is reinstantiated (since it is request scope) and the value in the textfield is passed to setCustomerId. When form is first displayed.findBalance}"/> / </h:form> </fieldset> … </h:body></html> 20 .. Input Form (customer-lookup.sun. BankForm is instantiated and getCustomerId is called. name. • Error message about invalid customer ID • What managed bean needs – Bean property corresponding to input element • xmlns:h="http://java. Otherwise.

public String findBalance() { customer = lookupService findCustomer(customerId).customerId = customerId. 22 . the bean is instantiated again (since it is requestscoped. if (customer == null) { return("unknown-customer"). p public void setCustomerId(String customerId) { this. When form submitted. } Called by JSF when form first displayed. } 21 BankForm.findCustomer(customerId).BankForm. the textfield is left blank initially. not session-scoped) and the value in the textfield is passed to this method. lookupService. } else { l Filled in by JSF before this action controller method is return("show-customer"). public String getCustomerId() { return(customerId). Part 1 (Bean Properties for Input Elements) @ManagedBean public class BankForm { private String customerId. Since it returns null in that case. } } This is the placeholder shown on next Part 2 (Action Controller Method) private static CustomerLookupService lookupService = new CustomerSimpleMap().

} } Filled in by the action controller method based on the value returned by the business logic.firstName} and #{bankForm. But no setter method is needed since this property does not correspond directly to di tl t iinput d t and thi property iis not automatically fill d iin b JSF t data. 23 Business Logic (Interface) public interface CustomerLookupService { public Customer findCustomer(String id) Part 3 (Placeholder for Results) private Customer customer.customer. } 24 .customer. d this t t t ti ll filled by JSF.otherProperties}. public Customer getCustomer() { return(customer). The getCustomer method is needed because the results page does #{bankForm.

"Polly". . 25 Business Logic (Implementation. (Implementation Continued) public Customer findCustomer(String id) { if (id!=null) { return(customers. )). "Coder".get(id. "Harry". addCustomer(new Customer("id001". } Provides some simple hardcoded test cases.toLowerCase())). } } 26 . "Codie".56)). 987654. customer). } } private void addCustomer(Customer customer) { customers. public CustomerSimpleMap() { customers = new HashMap<String. addCustomer(new Customer("id002". "Hacker".32)).78)). 1234.put(customer. } else { return(null). -3456. addCustomer(new Customer("id003".Customer> customers. y "Programmer".Customer>().getId().Business Logic (Implementation) public class CustomerSimpleMap implements CustomerLookupService { private Map<String.

com/jsf/html"> <h:head> … </h:head> <h:body> … <h2>No customer found with id "#{bankForm.customer.balanceNoSign}</li> </ul> … </h:body></html> 27 Results Page 2 (}</li> <li>Balance: $#{bankForm.jsf">try again</a>.w3.</p> … </h:body></html> 28 .Results Page 1 (show-balance.w3.xhtml) (unknown-customer xhtml) <!DOCTYPE …> <html xmlns="http://www w3 org/1999/xhtml" xmlns="> <h:head> … </h:head> <h:body> … <ul> <li>First name: #{bankForm.customer.customerId}"</h2> <p>Please <a href="customer-lookup.sun.firstName}</li> <li>Last name: #{bankForm.lastName}</li> #{ } / <li>ID: #{bankForm.sun.xhtml) (show-balance xhtml) <!DOCTYPE …> <html xmlns="http://www w3 org/1999/xhtml" xmlns= xmlns:h=" xmlns:h="http://java.

GWT. JSP. Spring.Results 29 © 2011 Marty Hall Prepopulating Input Fields p Customized Java EE Training: http://courses. Servlets. . At public venues or onsite at your location.0. Hibernate. Developed and taught by well-known author and developer.coreservlets. JSF 2. Java 6. Ajax. jQuery. RESTful Web Services.

that is initial selection. If value of getC is non-empty.Dual Roles • Bean property refers to both getter & setter – The getter method is called when form is displayed. as initial value of textfield. then getB on that result. Textfields • Example 1 – <h:inputText value="#{someBean. Only last one becomes setter.c}"/> • When form initially displayed. take the value in the textfield and p pass it to setSomeProperty. If value is something other than null or empty String. use it as initial value of textfield. and affects what is initially displayed to user – The value from the input element is passed to the setter method when the form is submitted • Examples p – <h:inputText…/> (textfield) • If getter returns non-empty (not null or "").someProperty}"/> • When form initially displayed. p y • Example 2 (Chaining) – <h:inputText value="#{someBean.a. – <h:selectBooleanCheckbox…/> (checkbox) • Getter returns true: initially checked. fields. • When form submitted. call getSomeProperty. When f b i d ll A h B h l Then take the value in the textfield and pass it to the setC method of that final result. this is initial value inside textfield Not used for password fields textfield. call getA. use it g py g. Otherwise top entry is initially selected. Otherwise unchecked – <h:selectOneMenu…/> (combobox.b. • Wh form submitted. 32 . call getA. then getB on that result. drop down menu) 31 • If return value of getter matches an entry in menu. then getC on that.

make that initially shown item. make checkbox initially p y y checked. If result matches any of the entries. you must add an entry for the f: namespace to the html start tag at top of file . The name could be either isSomeProperty (most common) or g getSomeProperty.someProperty}"> <f:selectItems value #{someBean. method. • When form submitted. buttons 33 Drop Down Menus (Comboboxes) • Example – <h:selectOneMenu value="#{someBean.Checkboxes • Example – <h:selectBooleanCheckbox value="#{someBean. This gives SelectItem[]) the entries in the drop down menu. but the simplest just takes a String: the value that will go in the menu. make checkbox initially unchecked.x does) to clear out old values of session-scoped checkboxes or radio buttons. If value is false. due to the f:selectItems tag. 34 – Note that. y p – There are several forms of the SelectItem constructor. which must be of type boolean or Boolean. pass the current selection to setSomeProperty. call getChoices (which should return List<SelectItem> or SelectItem[]). If value is true. Otherwise use top item. • When form submitted. Then call getSomeProperty.choices}"/> </h:selectOneMenu> • When form initially displayed. pass either true or false to setSomeProperty (which expects boolean or Boolean) – Note that JSF does not require anything (such as Struts 1.someProperty}"/> • When form initially displayed call the accessor method displayed.choices} / f:selectItems value="#{someBean.

• Shown briefly here but covered in detail in later section 35 Input Form – Top (study-plan-input. Make down menu second fa orite lang age choices be the languages for which app has study guides. li ti – Two" xmlns:h="http://java. we must declare the f: namespace. 36 .org/1999/xhtml xmlns:f="http://java. Requires looping tag. Give recommended computer study plan.Example • Idea – Collect input about programming background and ll i b i b k d d preferences.sun. Initial selection based on logic in app • Results page – List of recommended languages. • Input form – Textfield for favorite language.sun. Prepopulate based on most popular language in the application – Drop do n men for second-favorite"> <h:head> … </h:head> Since we use the f:selectItems tag for the drop down menu. Make initial choice the second most popular language in the th application.w3.xhtml) (study-plan-input xhtml) <!DOCTYPE …> <html xmlns="http://www w3 org/1999/xhtml" xmlns= http://www.

Steve Balmer.favoriteLanguage}"/><br/> Second favorite language: <h:selectOneMenu value="#{trainingForm. } // Options for dropdown box. LanguageUtils findMostPopularLanguage(0). private String favoriteLanguage = LanguageUtils. Th getters f ll The tt for // the boolean properties start with is.liar}"/><br/> <h:commandButton value="Show Recommended Study Plan" action= #{trainingForm. not get public Li t S l tIt bli List<SelectItem> getAvailableLanguages() { tA il bl L () return(LanguageUtils.languageList()).expert}"/><br/> Personally know Larry Page.Input Form – Bottom (study-plan-input.findMostPopularLanguage(0). private String secondFavoriteLanguage = LanguageUtils. See later slide. private pri ate boolean isE pert = tr e isExpert true.emailAddress}"/><br/> Favorite language: <h:inputText value="#{trainingForm.secondFavoriteLanguage}"> <f:selectItems value="#{trainingForm.showTrainingPlan} /> action="#{trainingForm showTrainingPlan}"/> </h:form> … </h:body></html> 37 Managed Bean (Part 1 – Properties for Input Elements) @ManagedBean public class TrainingForm { private String emailAddress.availableLanguages}"/> # / </h:selectOneMenu><br/> Programmed for 5+ years? <h:selectBooleanCheckbox value="#{trainingForm. // G tt Getters and setters f d tt for all. private boolean isLiar = false. and James Gosling? <h:selectBooleanCheckbox value="#{trainingForm.xhtml) (study-plan-input xhtml) <h:body> … <h:form> Email address: <h:inputText value="#{trainingForm.findMostPopularLanguage(1). 38 .

public List<String> getLanguagesToStudy() { return(languagesToStudy).randomLanguages(numLanguagesToStudy). } } 39 Managed Bean (Part 3 – Placeholder for Results) private List<String> languagesToStudy. if (isExpert) { numLanguagesToStudy = 4.Managed Bean (Part 2 – Action Controller) public String showTrainingPlan() { int numLanguagesToStudy. Since it can be of varying length. return("study-plan"). } ( ) if (isLiar) { This List is the placeholder that is filled in. } 40 . return("liar"). } else { numLanguagesToStudy = 2. the results page will need to use a loop. } else { languagesToStudy = LanguageUtils.

for(String language: languages) {"> <h:head>…</h:head> <h:body> … <ul> <ui:repeat var="language" value="#{trainingForm. "Scala" }. so if you are using a non-Java-EE-6 server. you must include the JSTL JAR files with your app.w3. "C++". "JavaScript".sun. "Python".com/jsf/html" xmlns:ui="http://java. "Perl". } 41 … Main Results Page (study-plan. But the basic idea is simple: identical to the JSTL c:forEach loop and very similar to the Java for(Blah b: collectionOfBlahs) xmlns:h="http://java.xhtml) (study-plan xhtml) <!DOCTYPE …> <html xmlns="http://www w3 org/1999/xhtml" xmlns= http://www. "PHP". g g static { availableLanguages = new ArrayList<SelectItem>(). "Ruby".sun. p private static List<SelectItem> availableLanguages.Helper Class (Code for Options in Dropdown) public class LanguageUtils { private static String[] languages = { "Java". } } public static List<SelectItem> languageList() { return(availableLanguages).add(new SelectItem(language)).languagesToStudy}"> <li>#{language}</li> </ui:repeat> </ul> … There Th iis a whole separate tutoriall section on llooping and h dli variableh l t t t i ti i d handling i bl </h:body></html> length data. This uses JSTL behind the scenes. "C#". 42 .

</p> … </h:body></html> Insulting your users is not generally considered a recommended practice.w3. but be honest this time. And you know more JavaScript than g . pp Brendan Eich or Doug Crockford.xhtml) (liar xhtml) <!DOCTYPE …> <html xmlns="http://www w3 org/1999/xhtml" xmlns="> <h:head>…</h:head> <h:body> … <h2> xmlns:h="http://java.“Error” Page (liar. right.jsf">try again</a>. 43 Results (Input Form) 44 .sun. I suppose?</h2> <p>Please <a href="study-plan-input.

Android. Ajax. Java 6. . Spring. At public venues or onsite at your location. jQuery. Hibernate. GWT.0.Results (Results Pages) 45 © 2011 Marty Hall Getting the Request p j and Response Objects Customized Java EE Training: http://courses. JSP.coreservlets. RESTful Web Services. Developed and taught by well-known author and developer. JSF Servlets.

User-Agent) • Looking up requesting host name – Uses for response object • S Setting status codes • Setting response headers • Setting long-lived cookies 47 Solution • Static methods – If they are needed..g. use static method calls to get them h d d i h d ll h ExternalContext context = FacesContext.g.g..getRequest().. environment.getResponse(). • Note • In some environments you cast results of getRequest and environments. PortletRequest and PortletResponse 48 . getResponse to values other than HttpServletRequest and HttpServletResponse – E g in a portlet environment you might cast result to E. HttpServletRequest request = (HttpServletRequest)context.. where action controller method (execute) gets request and response automatically • Why this matters – Uses for request object • Explicit session manipulation – E.g. changing inactive interval or invalidating session • Explicit cookie manipulation (e. long-lived cookies) • Reading request headers (e g User Agent) (e. HttpServletResponse response = (HttpServletResponse)context.Problem • No automatic access to request & response – JSF action controller methods do not have direct access • Unlike in Struts.getExternalContext().getCurrentInstance().

org/1999/xhtml" p // g/ / xmlns:f="http://java."> <h:head>…</h:head> <h:body> h b d … <h:form> Search String: g <h:inputText value="#{" xmlns:h="http://java.sendRedirect • Must use static methods to get the HttpServletResponse 49 – Return normal strings for error pages Input Form (search-engine-form.Example • Idea – Collect a search string and a search engine with the URLh // l / h? ) i h h URL encoded search string – Do}"/> </h:form> </h:body></html> 50 . show the results of a search with that search engine.w3..searchEngine}"> <f:selectItems value="#{searchController. y g pp pp • Managed bean – Construct a URL by concatenating a base URL (e.sun.sun.searchString}"/><br/> Search Engine: <h:selectOneMenu value="#{searchController. • Input form – Use textfield for arbitrary search string.searchEngineNames}"/> <f l tIt l "#{ hC t ll hE i N }"/> </h:selectOneMenu><br/> <h:commandButton value="Search" action="#{searchController. Use drop down menu to list only search engines that app supports.xhtml) (search-engine-form xhtml) <!DOCTYPE …> <html xmlns="http://www.

String searchURL = SearchUtilities.length() == 0)) { return("no-search-string").makeURL(searchEngine. } public void setSearchEngine(String searchEngine) { this. HttpServletResponse response = (HttpServletResponse)context.trim(). } else { return("unknown-search-engine"). } } 52 . return(null).getResponse().encode(searchString.searchEngine = searchEngine.getCurrentInstance(). if (searchURL != null) { ExternalContext context = t lC t t t t FacesContext. "utf-8").Managed Bean (Part 1 – Properties for Input Elements) @ManagedBean p public class SearchController { private String searchString. } public List<SelectItem> getSearchEngineNames() { return(SearchUtilities. } searchString = URLEncoder.sendRedirect(searchURL). } 51 Managed Bean (Part 2 – Action Controller) public String doSearch() throws IOException { if ((searchString.getExternalContext(). searchEngine. } public String getSearchEngine() { return(searchEngine). searchString). } public void setSearchString(String searchString) { this. public String getSearchString() { return(searchString).searchEngineNames()). (HttpServletResponse)context getResponse(). response.searchString = searchString.

Results (Input Form) 53 Results (Forwarding Results) 54 .

xml or by one of the new faces config xml annotations (e. jQuery. application q pp – Specified in faces-config.0. custom – Specified either in faces-config. session.0 basics with annotations. Android. • JSF Servlets. JSF 2. none. • JSF 1.coreservlets. Developed and taught by well-known author and developer. GWT.© 2011 Marty Hall Review of Bean Scopes Customized Java EE Training: http://courses. application. Java 6.x scopes – Request. Ajax. @SessionScoped) – Request scope is still the default 56 . view. Spring.. Hibernate.xml – Request scope is the default Examples of the use of bean scopes given in tutorial section on JSF 2. Bean Scopes • Idea – Designates how long managed beans will stay “alive”. JSP. and which users and requests can access previous bean instances. RESTful Web Services. At public venues or onsite at your location. session.0 scopes 20 – Request.g.

• New scope in JSF 2. Useful for beans that are p p referenced by other beans that are in scopes.0. • New scope in JSF 2. • Bean should implement Serializable • @CustomScoped(value="#{someMap}") – Bean is stored in the Map. same bean instance is used. You should make bean Serializable. Since beans are also used for initial values in input form. and programmer can control lifecycle.0 58 . • @ApplicationScoped – Put bean in application scope. • New scope in JSF 2 0 2. • @SessionScoped – Put bean in session scope.g. once when form is submitted). this means bean is generally instantiated twice (once when form is displayed. If same user with same cookie returns before session timeout. with event handlers or Ajax).0 • @NoneScoped – Bean is not placed in a scope.Annotations to Specify Bean Scope • @RequestScoped – Default. Shared by all users.. Bean pp p y either should have no state or you must carefully synchronize access. 57 Annotations to Specify Bean Scope (Continued) • @ViewScoped – Same bean instance is used as long as same user is on same page (e. Make a new instance for every HTTP request.

0. Ajax. Java 6.getResponse(). Spring.getCurrentInstance(). HttpServletResponse response = (HttpServletResponse)context. JSP. RESTful Web Services.getExternalContext().com/ Servlets.coreservlets. Summary • Beans generally have three sections – Bean properties to represent input elements • A pair of getter and setter methods for each – Action controller method – Placeholder for results data • Prepopulating input elements p p g p – <h:inputText value="#{customer. At public venues or onsite at your location. GWT. Android.firstName}"/> • When form displayed. jQuery. Developed and taught by well-known author and developer. HttpServletRequest request = (HttpServletRequest)context. value passed to setFirstName s bmitted al e • Getting the request and response objects ExternalContext context = FacesContext.© 2011 Marty Hall Wrap-Up Customized Java EE Training: http://courses. JSF 2.getRequest(). 60 . Hibernate. getFirstName called • When form submitted.

JSF 2. Servlets.coreservlets. . jQuery. At public venues or onsite at your location.0. Hibernate. JSP. RESTful Web Services. GWT. Developed and taught by well-known author and developer.© 2011 Marty Hall Questions? Customized Java EE Training: http://courses. Java 6. Ajax. Spring.