Handouts Apache MyFaces Session Slide 5 JSF is a new technology - - PDF document

handouts apache myfaces session
SMART_READER_LITE
LIVE PREVIEW

Handouts Apache MyFaces Session Slide 5 JSF is a new technology - - PDF document

Handouts Apache MyFaces Session Slide 5 JSF is a new technology that enables you to create Java-based web apps. It is more than only a new framework/technology; it is a widely adopted industrial standard. Since JSF provides a clear lifecycle


slide-1
SLIDE 1

Handouts Apache MyFaces – Session

Slide 5 JSF is a new technology that enables you to create Java-based web apps. It is more than only a new framework/technology; it is a widely adopted industrial standard. Since JSF provides a clear lifecycle to process HTTP requests, it is much cleaner and simpler than JSP/Servlet based development. The lifecycle, for instance, takes care of extracting request parameters and copies them to a corresponding JavaBean class. JSF enables you to uses POJO (Plain Old Java Objects) during your development process. Those classes are called backing beans. So there is no need to extend framework classes or implement special interfaces. It’s up to you if your class needs to inherit by a class of your domain specific framework or not. JSF provides a set of user interfaces components (UI components) that are itself JavaBeans with special properties. The concept behind the UI components is similar to that what is known by classic GUI frameworks like Swing. Since JSF focuses on web development it provides no fat client components. Instead it ships some generic components like UIInput

  • r UIOutput. It additionally provides some components that have special HTML properties

like HtmlSecret or HtmlTextArea extending the generic UIInput component. For adding new behaviour to the framework components, you could provide a custom component that extends some of the generic or standard HTML components. Since the UI components are standard JavaBeans they need to take care of their rendering. It is possible that a component renders itself or better that it delegates the rendering to a special class called

  • Renderer. A set of Renderer classes is called RenderKit. The JSF standard says that

each implementation must contain at least a RenderKit for HTML 4.0.1. But it is possible to create a custom RenderKit. Another interesting point is that JSF is able to handle events that are generated from the web GUI (the UI components). There are currently two concrete events (ActionEvent and ValueChangedEvent). Similar to the event concept in the JavaBean standard, JSF provides Listeners for each event. And again, it is possible to create custom events, since the two concrete event classes extend the abstract FacesEvent class, which is itself a specialization of the java.util.EventObject. Beyond these possibilities, you can call your back-end data by special Command components like HtmlCommandButton or HtmlCommandLink. These command components are used during the workflow process to present pages to the browser. For its management of managed-beans, JSF uses the dependency injection pattern that is know from lightweight IoC containers like Spring or Hivemind. It uses one special dependency injection pattern, the setter injection pattern. With the usage of setter injection it is possible to preconfigure properties of your backing beans. Additional to backing beans the “Managed Bean Facility” of JSF can also initialize and create other objects like DAO

  • bjects, for instance.

A very interesting point of JSF is that it contains a concept for converter objects. So you can add a converter to an input field and the input-string is automatically converted to a java.util.Date object. During rendering, it then converts the Date object to a String by

slide-2
SLIDE 2

utilizing a pattern for the date format (uses SimpleDateFormat). So the DateTimeConverter does not! call Date.toString(). There are other convertes like Number- or FloatConverter. Furthermore, it is again possible to create custom converters that map an input-String to your domain specific classes. Slide 6 JSF provides a special lifecycle to process HTTP requests. The lifecycle contains six phases.

  • 1. Restore View

A request was sent from the browser to the FacesServlet. It extracts the viewId (page name). The viewId is needed to lookup the components for that specific view. If it is the first request it creates them and wires the converters or event handlers to the

  • components. If the component tree is already created, the FacesServlet reuses it.
  • 2. Apply Request Values

JSF retrieves the (submitted) values of the components from the http-request. Those values are “copied” to the their correspondent ui component.

  • 3. Process Validations

This phase tries to convert the parameters (which are strings) to the specific type of the UI component property (e.g. Float). After component properties are containing the submitted values, JSF starts to validate these values. Validations can be type dependent, as for instance checking the allowed range of a Float value. To check a Float range, the value must be a Float object, that’s why validation is following the conversion phase.

  • 4. Update Model Values

After JSF has checked the validity of all component properties’ values it is time to update the model. During this phase JSF copies the component bound values to the properties of the backing beans, which are wired to a corresponding UI component.

  • 5. Invoke Application

After the backing beans contain their desired data values it is time to use them to execute the business layer. JSF calls an action method of a backing bean which can in turn perform some logic on your back-end (e.g. a business delegate). The action method returns a String which is used to calculate the next page being displayed to the user.

  • 6. Render Response

This is the time to present the response to the browser. Slide 7 Here we see a JSP page, containing JSF components. Particularly, a form-component, containing two input fields and a button, is displayed. The input fields are bound to properties

  • f a backing bean. The button is bound to a method of the backing bean.

Slide 8 Here is the corresponding backing bean class. You see a very simple and clean JavaBean

  • bject containing two properties and its setter/getter methods. Those properties are filled by
slide-3
SLIDE 3

the JSF lifecycle. After the properties are initialized, you could use them inside of the action method (send()). Action methods must be public, no-argument methods and need to return a String. The String is used inside of the application workflow to present pages to the client. Slide 9 Here a simple but complete XML configuration file is displayed. It contains the Managed Bean Facility, which creates the backing beans on demand. It also contains the workflow area

  • f a JSF application. The settings are such that when the send() method returns fine, the

browser will display the output.jsp file. Slide 10 So what are the reasons for using JSF, since there are more frameworks that do something similar? Popular web frameworks are for instance Struts and Tapestry. A big point is that JSF is an industrial standard and it will be part of the next J2EE version. So every J2EE 5 server must ship an implementation of the JSF specification. That means there will be a big vendor support, not only on server side. Most common IDEs will support the standard as well; there are already many IDEs on the market which support JSF development one way or another. Furthermore, there will be a 3rd party market for UI components. Slide 12 MyFaces was “born” as inhouse application in Austria (Europe). The “founders” decided to make it public as open source. Since 2005 MyFaces is a toplevel project of Apache Software foundation. MyFaces 1.1.x has passed the TCK for JSF 1.1.!!! Slide 14 Since MyFaces is a complete JSF specification implementation it provides an implementation

  • f the API and of the implemention classes. Furthermore, it provides lot of custom

components and extensions. MyFaces also supports the JSR-168 portlet standard. MyFaces provides a lot of jars. You could have each artefact in a single jar file or also an all- in-one jar file. It’s up to you. And note, that MyFaces provides lot’s of example files! Slide 15 Using MyFaces in your web application is easy; there is near nothing that needs to be

  • configured. Perhaps you need to add a special ServletContextListener to your web.xml file

and all will be fine! The ServletContextListener uses Jakarta Digester to read the configuration file and inits the needed JSF infrastructure. If you would like to use some of the extensions it will be good to have a special ServletFilter nested in you’re your web.xml file. The Filter adds images and JavaScript files that are needed by some of MyFaces custom

  • components. Also it helps you to upload files with MyFaces. Note the performance of the

Filter is good! Slide 16

slide-4
SLIDE 4

MyFaces contains some other internal details which could be helpful during developing your JSF-apps. It provides some ServletContext parameters. ALLOW_JAVASCRIPT: This parameter tells MyFaces if javascript code should be allowed in the rendered HTML

  • utput. If javascript is allowed, command_link anchors will have javascript code that submits

the corresponding form. If javascript is not allowed, the state saving info and nested parameters will be added as url parameters. By default this parameter is true. DETECT_JAVASCRIPT: This parameter lets MyFaces detect itself if javascript code should be allowed in the rendered HTML output. Default value is "false". Setting this param to true should be combined with STATE_SAVING_METHOD "server" for best results. This is an EXPERIMENTAL feature. You also have to enable the JavaScriptDetectionFilter to get JavaScript detection working. PRETTY_HTML: If true, rendered HTML code will be formatted, so that it is "human readable". For instance additional line separators and whitespace will be written, that do not influence the HTML

  • code. By default it is "true".

AUTO_SCROLL: If true, a javascript function will be rendered that is able to restore the former vertical scroll

  • n every request. Convenient feature if you have pages with long lists and you do not want

the browser page to always jump to the top if you trigger a link or button action that stays on the same page. Default value is "false". Dummy Form: A common mistake for beginners in developing a JSF application is to forget that HtmlCommandLinks must be wrapped in a Form-Object. So MyFaces does that automatically for you if this parameter is enabled. Please note, that these features are none-standard, and they don’t work in other implementations! Slide 18 The MyFaces calendar is a pretty calendar component. It allows you to create date centric application like flight bookers for instance. You must wrap each inputCalendar into a form-

  • bject. The calendar can be rendered as a popup or the classic way.

Slide 19 A special feature of MyFaces is that it enables you to handle uploads. The JSF spec (currently version 1.2) does not contain any information regarding uploads. So MyFaces added this feature since most real world web apps need file uploads. The fileupload component is based upon Jakarta Commons FileUpload component. So we reuse a feature that has shown its stability in many other frameworks like Struts. To use this feature you must register the ExtensionFilter in your web.xml file. Also keep in mind that UploadForms need a special enctype value. The backing bean property should be an object of interfaces UploadedFile. The tag has an attribute “accept” - specify the desired contentType for the uploaded file (e.g “application/x-pdf”) inside it; a nice feature for an upload component. An interesting point is

slide-5
SLIDE 5

that the WHAT working group (Web Hypertext Application Technology) has specified such an attribute for the standard input html field (type=”file”) see http://www.whatwg.org for more information. Inside your web.xml you also specify the maximum size of the uploaded file. Slide 20 MyFaces provides currently two tree implementations. This slide introduces the tree2 component, which is the newer one of the two tree components. It was a contribution by Sean Schofield, now committer of MyFaces, who migrated a Struts component to JSF. The component also contains code/concepts/ideas from Hans Bergsten’s “JavaServer Faces” book, who accepted the usage of his ideas in this MyFaces component. The tree component has a programmable API (TreeNode and TreeNodeBase) the layout can be defined in your JSP page, which contains the JSF components. You can use the JSF specific facet component for defining the layout. It is possible to use the tree for navigation cases by using the HtmlCommandLink component. Slide 21 You create your tree by creating a TreeNodeBase instance. The constructor needs three

  • arguments. The type, the description and a boolean value defining if the TreeNode is a leaf or
  • not. You can add new nodes by modifying a List object. That List object can be accessed

by calling getChildren(). Slide 22 To present the tree and its data we use the <x:tree2/> tag inside a JSP page. With the value attribute you refer to the tree data. The attribute clientSideToggle tells the component to use JavaScript or not. The var attribute allows you to access each Node inside

  • f the tree. The varNodeToggler attribute allows you to access the toggle

(t.nodeExpanded). The layout is defined in the standard facet tag of JSF (<f:facet/>). The facet name is the type you added before inside your data definition (backing bean). Each Facet contains a standard panelGroup that contains the stuff you want to present. This example contains a link, an image and a text. But that is up to you. Slide 23 The TabbedPane UI component of MyFaces is a nice component that allows you to “split” a form into sub tabs. It contains two custom tags. One for the root of the component (<x:panelTabbedPane/>) and one for each tab (<x:panelTab/>). Inside of the tab you can resuse standard input components like <h:inputText />. Since changing the current tab ends up in a request, the tabbedPane saves the state of each tab. So you can use it out of the box. Slide 24

slide-6
SLIDE 6

An example of the <x:panelTabbedPane/> component: You see one tabbedPane component, that contains two tabs. Inside of the first tab there are

  • nly standard components. So tabbedPane is easy to use. Migrating a large standard form to a

TabbedPane is not difficult. At least you must add a submit button (here <h:commandButton/>) to submit the stuff. Slide 25 JSF provide a UIData component that can deal with Arrays or Collections. MyFaces provides a custom table component that extends the features of the default (standard) UIData

  • component. Some features are:

preserveDataModel: Indicates whether the state of the whole DataModel should be saved and restored. Default value is “false”. sortColumn: Value reference to a model property that gives the current sort column name. sortAscending: Value reference to a model property that gives the current sort direction. preserveSort: Indicates whether the state of the sortColumn and sortAscending attribute should be saved and restored and written back to the model during the update model phase. By default it is true. renderedIfEmpty: Indicates whether this table should be rendered if the underlying DataModel is empty. You could as well use rendered="#{not empty bean.list}", but this one causes the getList method

  • f your model bean being called up to five times per request, which is not optimal when the

list is backed by a DB table. Using renderedIfEmpty="false" solves this problem, because the MyFaces extended HtmlDataTable automatically caches the DataModel and calls the model getter only once per

  • request. By default: “true”

rowIndexVar: A parameter name, under which the current rowIndex is set in request scope similar to the var parameter. The custom data component is the base for the special MyFaces table features like sortable and scrollable data. Slide 26 The dataSroller component allows you to scroll through a UIData component. It has several Facet components that allows a developer to add the “real” scroll mechanism.

slide-7
SLIDE 7

Here are the facets. first last next previos fastforward fastrewind On the slide you see a UIData component (MyFaces specific data component) with ID “data”. This component contains a large Array of Objects. To display not all of the stuff on one web page we added the scroller (<x:dataScroller). It is important that you add the scroller AFTER the corresponding UIData component (that is a know issue in JSF spec 1.0 and 1.1). Additionally, you must specify in a “for” attribute for which UIData component you want to use the scroller. Inside of the scroller component you can add standard Facet tags that allow you to browse/scroll through the UIData. A facet can take any standard JSF component you like (e.g. <h:grapicImage/> or <h:outputText/>). Slide 27 To use the sortable table component you put the <x:dataTable/> inside of your JSP page. Then specify the attributes sortColumn, sortAscending and preserveSort. Make sure that your backing bean has a sort method like: protected void sort(final String column, final boolean ascending) { Comparator comparator = new Comparator() { public int compare(Object o1, Object o2) { Worker w1 = (Worker)o1; Worker w2 = (Worker)o2; if (column == null) { return 0; } //sorting the “name” property of the worker object. if (column.equals("name")) { return ascending ? w1.getName().compareTo(w2.getName()) : w2.getName().compareTo(w1.getName()); } else if (column.equals("id")) { //similar, but only for “id” property of worker object } else return 0; } }; //sorting the collection. Collections.sort(workers, comparator); } And note that you call the sort() method inside of getWorkers(), before you return the (now sorted) collection of worker objects.

slide-8
SLIDE 8

Slide 28 JSF introduces a unique ID for each component, so the component can be looked up in the complete component tree. When you nest components inside of other components (and the nesting components are so called naming-containers) the IDs are concatenated like in “parentComponent:childComponent”. That causes problems when you would like to use your old (legacy) JavaScripts. The getElementById(); must be overwritten. That causes a lot of work. But MyFaces helps you here. Since MyFaces provides a custom implementation

  • f each standard component (e.g. <x:inputText />), you can use those components and

set the forceId attribute to true. Using this approach, your old JavaScript libraries are still

  • working. It is very interesting that the JSF spec. 1.2 contains a similar concept for forcing the

ID of a component, probably influenced by the MyFaces implementation. Slide 29/30 MyFaces allows you to simplify passing parameter to a backing bean. In standard JSF you are passing your parameters with <f:param> and read them by reading RequestParameterMap. MyFaces has an easy to use component for that. The updateActionListener passes an object (value) to a backing bean property (property) Slide 31 JSF introduces a small size of validators, but the standard allows you to create custom validator components. MyFaces contains several interesting custom validators. For the most

  • f them, MyFaces uses the Jakarta Commons Validators logic internally, which are used also

in Struts. You have to nest validators inside of an input component like shown on the slide. There are three known attribute validators:

  • <x:validateEmail/>
  • <x:validateISBN/>
  • <x:validateCreditCard/>

The <x:validateRegExpr/> has a pattern attribute which takes your regular expression. That component also the Jakarta Commons Validator implementation and not the regular expression support of Java 1.4. The <x:validateEqual/> is able to validate confirmed input like for passwords. Nest the validator component inside the second input component and it makes sure that both values are equal. Slide 32 JavaServer Faces contains a simple concept for composing pages. It uses JSP tags to include

  • ther pages. Those JSP tag must be wrapped with a subview component. That is a naming

container for unique IDs. That style has a limitation, since the JSP tags are bound to file

  • names. So why not using Tiles or something similar for the CompositeView pattern ?

Slide 33

slide-9
SLIDE 9

Good news: MyFaces supports Tiles for page composing. So we reused a defacto-standard and itegrated it into the core of MyFaces. The MyFaces Tiles support works currently with MyFaces and with the RI or any other impl of the JSF SPEC, the struts-tiles jar file is needed though for this support. As a remedy, the Tiles developers are about to extract Tiles from Struts, so that you have a Tiles core and its adaptors for Struts, Velocity and JSF / MyFaces. MyFaces ships a custom ViewHandler that is able to read tiles definitions and serve the requests to Tiles pages. It uses (like Struts) an XML file containing the page definitions. Currently you must add none-tiles pages to that configuration file. To be able to use that ViewHandler add it to your faces-cnf.xml file like: <faces-config> <application> <view-handler>

  • rg.apache.myfaces.application.jsp.JspTilesViewHandlerImpl

</view-handler> </application> ... </faces-config> Slide 36 Since the JSF standard allows you to support any markup, MyFaces contains a special,

  • ptional RenderKit for supporting WML. So older cell phones can also browse through JSF

pages by using Apache MyFaces. The MyFaces WML RenderKit was a contribution by Jiri Zaloudek. It contains tags and components with special WML based attributes. Also the Renderer classes are designed to generate WML output. It uses XDoclet to generate most of the components, tag classes and the tld configuration file. To be able to use the WML RenderKit you must add it to your faces- configuration.xml like: <faces-config> <application> <default-render-kit-id> WML_BASIC </default-render-kit-id> </application> ... </faces-config> That is all you need. Well – you need to change your pages to make use of the WML specific tags, since you want to present the cell phone browser its output. Slide 37 The MyFaces WML RenderKit is easy to use. The tags have names similar to their HTML

  • correspondent. There is a form and also an inputText component, for instance. You need

some special markup since the page is not a HTML page. In particular, the DOCTYPE is different as you can see on the slide. Furthermore, it is very important to set the right contentType with the <%@ page contentType="text/vnd.wap.wml" %>

  • statement. Notice that we are including wap and f as taglibs only. There will be no use of the
slide-10
SLIDE 10

HTML taglib, since the WAP browser can’t deal with that markup. However, with the f stuff you can add converters or validators like in the “common” html based pages. It is also possible to use the x taglib to use MyFaces specific validators. But as you see this page is very easy and not much different from an html based “Hello World” form. With this approach, you can rather easily add cell phone support to your web application. The model behind is still the same, since the backing beans are working with the WML RenderKit as well. Slides 38 and 39 How to create a JSF Portlet using MyFaces:

  • 1. Make sure your JSF MyFaces application runs as a stand-alone servlet.
  • 2. Remove any redirects from your faces-config.xml. Portlets can not handle these.
  • 3. Create a Portlet WAR as per the instructions of your Portlet container. Make sure it

contains everything that was included in step 1.

  • 4. Update your portlet.xml file as follows:

<!-- You must use this Portlet impl class --> <portlet-class>

  • rg.apache.myfaces.portlet.MyFacesGenericPortlet

</portlet-class> <!-- The "home page" of your JSF application --> <!-- This is a required param. --> <init-param> <name>default-view</name> <value>/some_view_id_from_faces-config</value> </init-param> <!-- A class name that implements

  • rg.apache.myfaces.portlet.DefaultViewSelector. This optional param is used if

your want to choose different default views based on some condition. You still must specify default-view above, but this impl will take precedence. --> <init-param> <name>default-view-selector</name> <value>com.foo.MyViewSelector</value> </init-param>

Slides 40

MyFAces has a sandbox project similar to Jakarta commons. Here components will grow up until they are ready for prime time. The component set contains different components and

  • extensions. From ajax components to form extension (for switching to https for instance)

Slides 41 -> 43 The Scheduler component is a web component, which enables you to “simulate” Evolution or

slide-11
SLIDE 11
  • ther know calendar applications. It has a JAVA-API to enable programmatic access to the

ScheduleModel and its Entries. ScheduleModel and ScheduleEntry are the base. Both interfaces have their implementations. The sample uses SimpleScheduleModel for accessing the ScheduleModel of the Scheduler component. If you are interested in your own model, go and extend the AbstractScheduleModel. Each Entry in the sample is DefaultScheduleEntry

  • bject.

Slides 44 It is important to nested the scheduler inside a form component (e.g. <h:form>). With the value attribute of the <s:scheduler> component you refer the current ScheduleModel of your backing bean. Slides 45 Since the cool JavaScript lib “script.aculo.us” was introduced, MyFaces contains some very nice visual effects, based upon “script.aculo.us”. With the effects component you can create “magical” messages e.g. for validation or converter output.