12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 12 ■ PROCESSING AND NAVIGATION*doCreateBook-success/listBooks.htmManaged BeansAs noted earlier in this chapter, the MVC pattern encourages separation between the model, the view,and the controller: JSF pages form the view and the FacesServlet the controller. Managed beans are thegateway to the model.Managed beans are annotated <strong>Java</strong> classes and are central to web applications. They can performbusiness logic (or delegate to EJBs, for example), handle navigation between pages, and hold data. Atypical JSF application includes one or more managed beans that can be shared by several pages.The data is held <strong>with</strong>in attributes of the managed bean, also called a backing bean. A backing beandefines the data that a UI component is bound to (the target of a form, for example). To bindcomponents to a backing bean, you need to use the expression language.How to Write a Managed BeanWriting a managed bean is as easy as writing an EJB or a JPA entity; it’s simply a <strong>Java</strong> class annotated<strong>with</strong> @ManagedBean (see Listing 12-3). There are no faces-config.xml entries, no helper classes, norinheritance. While these things aren’t required, they are available if you want/need to use them. JSF 2.0also uses the configuration-by-exception mechanism, whereby, <strong>with</strong> only one annotation, you can useall defaults and deploy your web application <strong>with</strong> such a managed bean.Listing 12-3. A Simple Managed Bean@ManagedBeanpublic class BookController {private Book book = new Book();public String doCreateBook() {createBook(book);return "listBooks.xhtml";}}// Constructors, getters, settersListing 12-3 shows the programming model of a managed bean: it holds state (the book attribute),defines action methods (doCreateBook()) that are referenced in a page, and handles navigation (return"listBooks.xhtml").351

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!