jsf 2 0: managed beans jsf 2.0: managed beans – classes to...

30
© 2011 Marty Hall JSF 2 0: Managed Beans JSF 2.0: Managed Beans Classes to Represent Form Info Originals of Slides and Source Code for Examples: http://www.coreservlets.com/JSF-Tutorial/jsf2/ Customized Java EE Training: http://courses.coreservlets.com/ 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 t htt // lt / courses at http://courses.coreservlets.com/. Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. C d l d dt ht b M t H ll Customized Java EE Training: http://courses.coreservlets.com/ 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. Courses developed and taught by Marty Hall JSF, servlets/JSP, Ajax, jQuery, Android development, Java 6 programming, custom mix of topics Ajax courses can concentrate on 1 library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, etc.) or survey several Courses developed and taught by coreservlets.com experts (edited by Marty) Spring, Hibernate/JPA, EJB3, GWT, SOAP-based and RESTful Web Services Contact [email protected] for details

Upload: others

Post on 29-May-2020

22 views

Category:

Documents


0 download

TRANSCRIPT

© 2011 Marty Hall

JSF 2 0: Managed Beans –JSF 2.0: Managed Beans –Classes to Represent Form Info

Originals of Slides and Source Code for Examples:http://www.coreservlets.com/JSF-Tutorial/jsf2/

Customized Java EE Training: http://courses.coreservlets.com/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 t htt // l t /courses at http://courses.coreservlets.com/.

Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at

your organization.C d l d d t ht b M t H ll

Customized Java EE Training: http://courses.coreservlets.com/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.

• Courses developed and taught by Marty Hall– JSF, servlets/JSP, Ajax, jQuery, Android development, Java 6 programming, custom mix of topics– Ajax courses can concentrate on 1 library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, etc.) or survey several

• Courses developed and taught by coreservlets.com experts (edited by Marty)– Spring, Hibernate/JPA, EJB3, GWT, SOAP-based and RESTful Web Services

Contact [email protected] for details

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

5

© 2011 Marty Hall

Basic Beans andBasic Beans and “Managed” Beansg

Customized Java EE Training: http://courses.coreservlets.com/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 constructorsg 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 fieldsmethods 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

7

More on Bean Properties

• Usual rule to turn method into propertyD th d “ t” “ t” d h th t l tt t– Drop the word “get” or “set” and change the next letter to lowercase. Again, instance var name is irrelevant.

• Method name: getFirstName• Property name: firstName• Property name: firstName• Example: #{customer.firstName}

• Exception 1: boolean propertiesIf b l B l– If getter returns boolean or Boolean

• Method name: getPrime or isPrime• Property name: prime

Example: #{myNumber 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}

8

Bean Properties: Examples

Method N

Property N

Example JSF UNames Name JSF Usage

getFirstNamesetFirstName

firstName #{customer.firstName}<h:inputText value="#{customer.firstName}"/>

isExecutivesetExecutive(boolean property)

executive #{customer.executive}<h:selectBooleanCheckbox

value="#{customer executive}"/>(boolean property) value= #{customer.executive} />

getExecutivesetExecutive(boolean property)

executive #{customer.executive}<h:selectBooleanCheckbox

value="#{customer executive}"/>(boolean property) value= #{customer.executive} />

getZIPsetZIP

ZIP #{address.ZIP}<h:inputText value="#{address.ZIP}"/>

9

Note 1: property name does not exist anywhere in your code. It is just a shortcut for the method name.Note 2: property name is derived only from method name. Instance variable name is irrelevant.

Why You Should Use Accessors Not Public FieldsAccessors, Not Public Fields

• Bean rulesT b b h ld h bli fi ld– To be a bean, you should not have public fields.

– Wrongpublic double speed;

– Rightprivate double speed; // Var need not match method name

public double getSpeed() { return(speed);

}public void setSpeed(double speed) {

this.speed = speed; } Note: in Eclipse, after you create instance variable, if

you R-click and choose “Source”, it gives you option to

• OOP design– You should do this in all your Java code anyhow. Why?

10

you R click and choose Source , it gives you option to generate getters and setters for you.

Why You Should Use Accessors Not Public FieldsAccessors, Not Public Fields

• 1) You can put constraints on values

public void setSpeed(double newSpeed) {if (newSpeed < 0) {

sendErrorMessage(...);newSpeed = Math.abs(newSpeed);

}speed = newSpeed;

}

– If users of your class accessed the fields directly, then they would each be responsible for checking constraints.

11

Why You Should Use Accessors Not Public FieldsAccessors, Not Public Fields

• 2) You can change your internal i i h h i i frepresentation without changing interface

// Now using metric units (kph, not mph)// g ( p , p )

public void setSpeed(double newSpeed) {speedInKPH = convert(newSpeed);speedInKPH = convert(newSpeed);

}

p blic oid setSpeedInKPH(do ble ne Speed) {public void setSpeedInKPH(double newSpeed) {speedInKPH = newSpeed;

}

12

Why You Should Use Accessors Not Public FieldsAccessors, Not Public Fields

• 3) You can perform arbitrary side effects

public double setSpeed(double newSpeed) {speed = newSpeed;updateSpeedometerDisplay();

}

– If users of your class accessed the fields directly, then they would each be responsible for executing side effects. Too much work and runs huge risk of having displayToo much work and runs huge risk of having display inconsistent from actual values.

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 constructorZero arg constructor• No public instance variables• Use getBlah/setBlah or isBlah/setBlah naming conventions

JSF ft f t “b ti ”• JSF often refers to “bean properties”– Which are shortcuts for getter/setter methods

• getFirstName method: refer to “firstName”getFirstName method: refer to firstName– #{customer.firstName}

• isVeryCool method (boolean): refer to “veryCool”– #{invention veryCool}– #{invention.veryCool}

• getHTMLString method: refer to “HTMLString”– #{message.HTMLString}

14

Managed Beans

• JSF automatically “manages” the bean– Instantiates it

• Thus the need for a zero-arg constructor

– Controls its lifecycleControls its lifecycle• Scope (request, session, application) determines lifetime

– Calls setter methodsf #{ f /• I.e., for <h:inputText value="#{customer.firstName"/>,

when form submitted, the value is passed to setFirstName

– Calls getter methods• #{customer.firstName} results in calling getFirstName

• Declaring beansSi l t @M dB b f l– Simplest: @ManagedBean before class

– Most powerful: <managed-bean> in faces-config.xml• See separate section on navigation and faces-config.xml15

© 2011 Marty Hall

The Three Parts ofThe Three Parts of Managed Beansg

Customized Java EE Training: http://courses.coreservlets.com/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.

Overview

• Managed beans typically have three parts– Bean properties (i.e, pairs of getter and setter methods)

• One pair for each input element• Setter methods called automatically by JSF when formSetter methods called automatically by JSF when form

submitted

– Action controller methods• Often only one but could be several if the same form has• Often only one, but could be several if the same form has

multiple push buttons• Action controller method (corresponding to the button that

was pressed) called automatically by JSFwas pressed) called automatically by JSF

– Placeholders for results data• Not automatically called by JSF: to be filled in by action

t ll th d b d lt f b i l icontroller method based on results of business logic.

17

JSF Flow of Control (Simplified)(Simplified)

balance.xhtml

When form first displayed, getCustomerId is called. If it is non-empty, it becomes initial value of the textfield.balance.xhtml

Uses <h:commandButton … action="#{bankForm.findBalance}"/>

and <h:inputText value="#{bankForm.customerId}"/>

When form submitted, textfield value passed to setCustomerId.

submit formPOST t b l j f

Find return l

ChooseRun Action forward result1.xhtml

Run SetterMethods

BusinessLogic

results

The results get stored in the placeholder. E.g., a Customer that corresponds to the customer ID is found and placed in an instance variable of main bean.

POST request balance.jsf Bean value PageController Method result2.xhtml...

resultN.xhtmlUses

#{bankForm.someProperty}

This is the method listed in the action of h:commandButton (e.g., findBalance)

If bean is request-scoped, instantiate it. But for other scopes (e.g., session), you might use existing bean instance.

#{ p y}to display bean properties

18

This could be #{bankForm.customerId}, where customerId was passed in by the user, or it could be #{bankForm.customer.balance}, where getCustomerreturns the Customer object found by the business logic, and getBalancereturns that customer’s bank account balance.

Example

• Idea– Enter a bank customer ID– Get either

• Page showing first name last name and balance• Page showing first name, last name, and balance• Error message about invalid customer ID

• What managed bean needs– Bean property corresponding to input element

• I.e., getCustomerId and setCustomerId

Action controller method– Action controller method• Maps a customer ID to a Customer and stores the

Customer in an instance variable

l h ld f l d– Placeholder for results data• An initially empty instance variable (for storing the

Customer) and associated getter method.19

Input Form(customer-lookup xhtml)(customer-lookup.xhtml)

<!DOCTYPE …><html xmlns="http://www.w3.org/1999/xhtml"<html xmlns http://www.w3.org/1999/xhtml

xmlns:h="http://java.sun.com/jsf/html">…<h:body> This value plays a dual role. When form is first displayed, BankForm is instantiated and getCustomerId is called. If the value is

non-empty that result is the initial value of the textfield Otherwise the textfield is initially empty When the form is submitted

…<fieldset><legend>Enter Your Customer ID</legend>

/

non empty, that result is the initial value of the textfield. Otherwise, the textfield is initially empty. When the form is submitted, BankForm is reinstantiated (since it is request scope) and the value in the textfield is passed to setCustomerId.

<p>Legal ids are id001, id002, and id003.</p><h:form>Customer ID: <h:inputText value="#{bankForm customerId}"/><br/><h:inputText value="#{bankForm.customerId}"/><br/><h:commandButton value="Show Current Balance"

action="#{bankForm.findBalance}"/></h:form>/</fieldset>…</h:body></html>20

BankForm.java: Part 1 (Bean Properties for Input Elements)Properties for Input Elements)

@ManagedBean public class BankForm {public class BankForm { private String customerId;

public String getCustomerId() {

Called by JSF when form first displayed. Since it returns null in that case, the textfield is left blank initially.

public String getCustomerId() {return(customerId);

}When form submitted, the bean is instantiated again (since it is request-scoped, not session-scoped) and the value in the textfield is passed to this method.

public void setCustomerId(String customerId) {this.customerId = customerId;

}

p

}

21

BankForm.java: Part 2 (Action Controller Method)(Action Controller Method)private static CustomerLookupService lookupService =new CustomerSimpleMap();new CustomerSimpleMap();

public String findBalance() {customer = lookupService findCustomer(customerId);customer = lookupService.findCustomer(customerId);if (customer == null) {return("unknown-customer");

} l {} else {return("show-customer");

}}

Filled in by JSF before this action controller method is called.

}

This is the placeholder shown on next slide.

22

BankForm.java: Part 3 (Placeholder for Results)(Placeholder for Results)

private Customer customer;private Customer customer;

public Customer getCustomer() {return(customer); Filled in by the action return(customer);

}}

Filled in by the action controller method based on the value returned by the business logic.

The getCustomer method is needed because the results page does #{bankForm.customer.firstName} and #{bankForm.customer.otherProperties}. But no setter method is needed since this property does not correspond di tl t i t d t d thi t i t t ti ll fill d i b JSFdirectly to input data, and this property is not automatically filled in by JSF.

23

Business Logic (Interface)

public interface CustomerLookupService {public interface CustomerLookupService {public Customer findCustomer(String id);

}

24

Business Logic (Implementation)(Implementation)

public class CustomerSimpleMapimplements CustomerLookupService {implements CustomerLookupService {

private Map<String,Customer> customers;

public CustomerSimpleMap() {public CustomerSimpleMap() {customers = new HashMap<String,Customer>();addCustomer(new Customer("id001", "Harry",

"Hacker", -3456.78));, ));addCustomer(new Customer("id002", "Codie",

"Coder", 1234.56));addCustomer(new Customer("id003", "Polly",y

"Programmer", 987654.32));}

25

Provides some simple hardcoded test cases.

Business Logic (Implementation Continued)(Implementation, Continued)public Customer findCustomer(String id) {if (id!=null) {if (id!=null) {return(customers.get(id.toLowerCase()));

} else {return(null);return(null);

}}

private void addCustomer(Customer customer) {customers.put(customer.getId(), customer);

}}

26

Results Page 1(show-balance xhtml)(show-balance.xhtml)

<!DOCTYPE …><html xmlns="http://www w3 org/1999/xhtml"<html xmlns= http://www.w3.org/1999/xhtml

xmlns:h="http://java.sun.com/jsf/html"><h:head>…</h:head><h:body>……<ul><li>First name: #{bankForm.customer.firstName}</li><li>Last name: #{bankForm.customer.lastName}</li> #{ } /<li>ID: #{bankForm.customer.id}</li><li>Balance: $#{bankForm.customer.balanceNoSign}</li>

</ul> …</h:body></html>

27

Results Page 2(unknown-customer xhtml)(unknown-customer.xhtml)

<!DOCTYPE …><html xmlns="http://www w3 org/1999/xhtml"<html xmlns= http://www.w3.org/1999/xhtml

xmlns:h="http://java.sun.com/jsf/html"><h:head>…</h:head><h:body>…<h2>No customer found with id "#{bankForm.customerId}"</h2><p>Please <a href="customer-lookup.jsf">try again</a>.</p>……</h:body></html>

28

Results

29

© 2011 Marty Hall

PrepopulatingPrepopulatingInput Fieldsp

Customized Java EE Training: http://courses.coreservlets.com/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.

Dual Roles

• Bean property refers to both getter & setter– The getter method is called when form is displayed, and

affects what is initially displayed to user– The value from the input element is passed to the setter– The value from the input element is passed to the setter

method when the form is submitted

• Examplesp– <h:inputText…/> (textfield)

• If getter returns non-empty (not null or ""), this is initial value inside textfield Not used for password fieldsvalue inside textfield. Not used for password fields.

– <h:selectBooleanCheckbox…/> (checkbox)• Getter returns true: initially checked. Otherwise unchecked

– <h:selectOneMenu…/> (combobox; drop down menu)• If return value of getter matches an entry in menu, that is

initial selection. Otherwise top entry is initially selected.31

Textfields

• Example 1– <h:inputText value="#{someBean.someProperty}"/>

• When form initially displayed, call getSomeProperty. If value is something other than null or empty String, use it g p y g,as initial value of textfield.

• When form submitted, take the value in the textfield and pass it to setSomeProperty.p p y

• Example 2 (Chaining)– <h:inputText value="#{someBean.a.b.c}"/>

• When form initially displayed, call getA, then getB on that result, then getC on that. If value of getC is non-empty, use it as initial value of textfield. Wh f b i d ll A h B h l• When form submitted, call getA, then getB on that result. Then take the value in the textfield and pass it to the setCmethod of that final result. Only last one becomes setter.

32

Checkboxes

• Example– <h:selectBooleanCheckbox

value="#{someBean.someProperty}"/>• When form initially displayed call the accessor methodWhen form initially displayed, call the accessor method,

which must be of type boolean or Boolean. The name could be either isSomeProperty (most common) or getSomeProperty. If value is true, make checkbox initially g p y ychecked. If value is false, make checkbox initially unchecked.

• When form submitted, pass either true or false to setSomeProperty (which expects boolean or Boolean)

– Note that JSF does not require anything (such as Struts 1.x does) to clear out old values of session-scoped checkboxes or radio buttonsbuttons.

33

Drop Down Menus (Comboboxes)(Comboboxes)

• Example– <h:selectOneMenu

value="#{someBean.someProperty}"><f:selectItems value="#{someBean.choices}"/>f:selectItems value #{someBean.choices} /

</h:selectOneMenu>• When form initially displayed, call getChoices (which

should return List<SelectItem> or SelectItem[]) This givesshould return List<SelectItem> or SelectItem[]). This gives the entries in the drop down menu. Then call getSomeProperty. If result matches any of the entries, make that initially shown item. Otherwise use top item.y p

– There are several forms of the SelectItem constructor, but the simplest just takes a String: the value that will go in the menu.

• When form submitted, pass the current selection to setSomeProperty.

– Note that, due to the f:selectItems tag, you must add an entry for the f: namespace to the html start tag at top of file

34

Example

• Ideall i b i b k d d– Collect input about programming background and

preferences. Give recommended computer study plan.• Input formInput form

– Textfield for favorite language. Prepopulate based on most popular language in the applicationDrop do n men for second fa orite lang age Make– Drop down menu for second-favorite language. Make choices be the languages for which app has study guides. Make initial choice the second most popular language in th li tithe application.

– Two checkboxes. Initial selection based on logic in app• Results pageResults page

– List of recommended languages. Requires looping tag.• Shown briefly here but covered in detail in later section

35

Input Form – Top(study-plan-input xhtml)(study-plan-input.xhtml)

<!DOCTYPE …><html xmlns="http://www w3 org/1999/xhtml"<html xmlns= http://www.w3.org/1999/xhtml

xmlns:f="http://java.sun.com/jsf/core"xmlns:h="http://java.sun.com/jsf/html">

<h:head><h:head>…</h:head>

Since we use the f:selectItems tag for the drop down menu, we must declare the f: namespace.

36

Input Form – Bottom(study-plan-input xhtml)(study-plan-input.xhtml)

<h:body>…<h:form>Email address: <h:inputText value="#{trainingForm.emailAddress}"/><br/>Favorite language:Favorite language: <h:inputText value="#{trainingForm.favoriteLanguage}"/><br/>Second favorite language:<h:selectOneMenu value="#{trainingForm.secondFavoriteLanguage}">

# /<f:selectItems value="#{trainingForm.availableLanguages}"/></h:selectOneMenu><br/>Programmed for 5+ years? <h:selectBooleanCheckbox value="#{trainingForm.expert}"/><br/>Personally know Larry Page, Steve Balmer, and James Gosling?<h:selectBooleanCheckbox value="#{trainingForm.liar}"/><br/><h:commandButton value="Show Recommended Study Plan"

action="#{trainingForm showTrainingPlan}"/>action= #{trainingForm.showTrainingPlan} /></h:form>…</h:body></html>

37

Managed Bean (Part 1 –Properties for Input Elements)Properties for Input Elements)

@ManagedBean public class TrainingForm {public class TrainingForm {

private String emailAddress;private String favoriteLanguage =

LanguageUtils findMostPopularLanguage(0);LanguageUtils.findMostPopularLanguage(0);private String secondFavoriteLanguage =

LanguageUtils.findMostPopularLanguage(1);pri ate boolean isE pert tr eprivate boolean isExpert = true;private boolean isLiar = false;

// G tt d tt f ll Th tt f// Getters and setters for all. The getters for// the boolean properties start with is, not get

bli Li t S l tIt tA il bl L () {public List<SelectItem> getAvailableLanguages() {return(LanguageUtils.languageList());

} // Options for dropdown box. See later slide.38

Managed Bean (Part 2 – Action Controller)(Part 2 – Action Controller)public String showTrainingPlan() {int numLanguagesToStudy;int numLanguagesToStudy;if (isExpert) {numLanguagesToStudy = 4;

} else {} else {numLanguagesToStudy = 2;

}if (isLiar) {( ) {return("liar");

} else {languagesToStudy =

This List is the placeholder that is filled in. Since it can be of varying length,the results page will need to use a loop.

LanguageUtils.randomLanguages(numLanguagesToStudy);return("study-plan");

}}

39

Managed Bean (Part 3 –Placeholder for Results)Placeholder for Results)private List<String> languagesToStudy;

public List<String> getLanguagesToStudy() {return(languagesToStudy);

}}

40

Helper Class (Code for Options in Dropdown)in Dropdown)

public class LanguageUtils {private static String[] languages =private static String[] languages ={ "Java", "JavaScript", "C#", "C++", "PHP", "Python",

"Perl", "Ruby", "Scala" };private static List<SelectItem> availableLanguages;p g g

static {availableLanguages = new ArrayList<SelectItem>();for(String language: languages) {availableLanguages.add(new SelectItem(language));

}}

public static List<SelectItem> languageList() {return(availableLanguages);

}…

41

Main Results Page(study-plan xhtml)(study-plan.xhtml)

<!DOCTYPE …><html xmlns="http://www w3 org/1999/xhtml"<html xmlns= http://www.w3.org/1999/xhtml

xmlns:h="http://java.sun.com/jsf/html"xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head>…</h:head><h:head>…</h:head><h:body>…<ul><ui:repeat var="language"

value="#{trainingForm.languagesToStudy}"><li>#{language}</li>

</ui:repeat></ul>…

Th i h l t t t i l ti l i d h dli i bl</h:body></html>

42

There is a whole separate tutorial section on looping and handling variable-length data. But the basic idea is simple: identical to the JSTL c:forEach loop and very similar to the Java for(Blah b: collectionOfBlahs) loop. This uses JSTL behind the scenes, so if you are using a non-Java-EE-6 server, you must include the JSTL JAR files with your app.

“Error” Page(liar xhtml)(liar.xhtml)

<!DOCTYPE …><html xmlns="http://www w3 org/1999/xhtml"<html xmlns= http://www.w3.org/1999/xhtml

xmlns:h="http://java.sun.com/jsf/html"><h:head>…</h:head><h:body><h:body>…<h2>Yeah, right. And you know more JavaScript than Brendan Eich or Doug Crockford, I suppose?</h2>g , pp<p>Please <a href="study-plan-input.jsf">try again</a>, but be honest this time.</p>…</h:body></html>

43

Insulting your users is not generally considered a recommended practice.

Results (Input Form)

44

Results (Results Pages)

45

© 2011 Marty Hall

Getting the RequestGetting the Request and Response Objectsp j

Customized Java EE Training: http://courses.coreservlets.com/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.

Problem

• No automatic access to request & response– JSF action controller methods do not have direct access

• Unlike in Struts, where action controller method (execute) gets request and response automatically

• Why this matters– Uses for request object

• Explicit session manipulation• Explicit session manipulation – E.g., changing inactive interval or invalidating session

• Explicit cookie manipulation (e.g., long-lived cookies)• Reading request headers (e g User Agent)• Reading request headers (e.g., User-Agent)• Looking up requesting host name

– Uses for response objectS• Setting status codes

• Setting response headers• Setting long-lived cookies 47

Solution

• Static methodsIf h d d i h d ll h– If they are needed, use static method calls to get them

ExternalContext context =FacesContext.getCurrentInstance().getExternalContext();

HttpServletRequest request =(HttpServletRequest)context.getRequest();

HttpServletResponse response =(HttpServletResponse)context.getResponse();

• Note• In some environments you cast results of getRequest andIn some environments, you cast results of getRequest and

getResponse to values other than HttpServletRequest and HttpServletResponse

– E g in a portlet environment you might cast result to– E.g., in a portlet environment, you might cast result to PortletRequest and PortletResponse

48

Example

• Idea– Collect a search string and a search engine name, show

the results of a search with that search engine.

• Input form• Input form– Use textfield for arbitrary search string. Use drop down

menu to list only search engines that app supports.y g pp pp

• Managed bean– Construct a URL by concatenating a base URL (e.g.,

h // l / h? ) i h h URLhttp://www.google.com/search?q=) with the URL-encoded search string

– Do response.sendRedirectDo response.sendRedirect• Must use static methods to get the HttpServletResponse

– Return normal strings for error pages49

Input Form(search-engine-form xhtml)(search-engine-form.xhtml)

<!DOCTYPE …><html xmlns="http://www.w3.org/1999/xhtml"p // g/ /

xmlns:f="http://java.sun.com/jsf/core"xmlns:h="http://java.sun.com/jsf/html">

<h:head>…</h:head>h b d<h:body>…<h:form>Search String: g<h:inputText value="#{searchController.searchString}"/><br/>Search Engine: <h:selectOneMenu value="#{searchController.searchEngine}">

<f l tIt l "#{ hC t ll hE i N }"/><f:selectItems value="#{searchController.searchEngineNames}"/></h:selectOneMenu><br/><h:commandButton value="Search"

action="#{searchController.doSearch}"/></h:form></h:body></html>

50

Managed Bean (Part 1 –Properties for Input Elements)Properties for Input Elements)

@ManagedBeanpublic class SearchController {p {

private String searchString, searchEngine;

public String getSearchString() {return(searchString);

}public void setSearchString(String searchString) {

this.searchString = searchString;this.searchString searchString;}public String getSearchEngine() {

return(searchEngine);}public void setSearchEngine(String searchEngine) {

this.searchEngine = searchEngine;}}public List<SelectItem> getSearchEngineNames() {

return(SearchUtilities.searchEngineNames());}51

Managed Bean (Part 2 – Action Controller)(Part 2 – Action Controller)public String doSearch() throws IOException {

if ((searchString.trim().length() == 0)) {if ((searchString.trim().length() 0)) {return("no-search-string");

}searchString = URLEncoder.encode(searchString, "utf-8");String searchURL =

SearchUtilities.makeURL(searchEngine, searchString);if (searchURL != null) {

t lC t t t tExternalContext context =FacesContext.getCurrentInstance().getExternalContext();

HttpServletResponse response =(HttpServletResponse)context getResponse();(HttpServletResponse)context.getResponse();

response.sendRedirect(searchURL);return(null);

} else {return("unknown-search-engine");

} }

52

Results (Input Form)

53

Results (Forwarding Results)(Forwarding Results)

54

© 2011 Marty Hall

Review of Bean Scopes

Customized Java EE Training: http://courses.coreservlets.com/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.

Bean Scopes

• Idea– Designates how long managed beans will stay “alive”,

and which users and requests can access previous bean instances.instances.

• JSF 1.x scopes– Request, session, applicationq pp– Specified in faces-config.xml– Request scope is the default

JSF 2 0

Examples of the use of bean scopes given in tutorial section on JSF 2.0 basics with annotations.

• JSF 2.0 scopes– Request, session, application, view, none, custom

Specified either in faces config xml or by one of the new– Specified either in faces-config.xml or by one of the new annotations (e.g., @SessionScoped)

– Request scope is still the default56

Annotations to Specify Bean ScopeScope

• @RequestScoped– Default. Make a new instance for every HTTP request.

Since beans are also used for initial values in input form, this means bean is generally instantiated twice (oncethis means bean is generally instantiated twice (once when form is displayed, once when form is submitted).

• @SessionScoped– Put bean in session scope. If same user with same cookie

returns before session timeout, same bean instance is used. You should make bean Serializable.used. You should make bean Serializable.

• @ApplicationScoped– Put bean in application scope. 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)Scope (Continued)

• @ViewScoped– Same bean instance is used as long as same user is on

same page (e.g., with event handlers or Ajax). • New scope in JSF 2 0New scope in JSF 2.0. • Bean should implement Serializable

• @CustomScoped(value="#{someMap}")– Bean is stored in the Map, and programmer can control

lifecycle.• New scope in JSF 2.0New scope in JSF 2.0

• @NoneScoped– Bean is not placed in a scope. Useful for beans that are p p

referenced by other beans that are in scopes. • New scope in JSF 2.0

58

© 2011 Marty Hall

Wrap-Up

Customized Java EE Training: http://courses.coreservlets.com/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.

Summary

• Beans generally have three sections– Bean properties to represent input elements

• A pair of getter and setter methods for each

– Action controller method– Action controller method– Placeholder for results data

• Prepopulating input elementsp p g p– <h:inputText value="#{customer.firstName}"/>

• When form displayed, getFirstName calledWhen form s bmitted al e passed to setFirstName• When form submitted, value passed to setFirstName

• Getting the request and response objectsExternalContext context =

FacesContext.getCurrentInstance().getExternalContext();HttpServletRequest request = (HttpServletRequest)context.getRequest();HttpServletResponse response = (HttpServletResponse)context.getResponse();

60

© 2011 Marty Hall

Questions?

Customized Java EE Training: http://courses.coreservlets.com/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.