Java Server Faces (JSF) Introduction - Lehman

2y ago
21 Views
2 Downloads
2.56 MB
100 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Audrey Hope
Transcription

CMP 436/774Introduction toJava Server faces (JSFs)-Part 1Fall 2012Department of Mathematicsand Computer ScienceLehman College, CUNY1Java Server Faces (JSF)Introduction21

References Chapters 4-12 (of the reference R1: Java EE 6 Tutorial)Chapters 4, 5 (of the reference 5: David R Heffelfinger , Java EE 6Development with NetBeans 7)JSF 2.0 from reference 4 (from www.coreservlets.com)Other references ?print yesAnd other URLs (updated)3Java Server Faces (1) Most Java Web applications are developed using well known webapplication frameworks such as Apache Struts, Spring, and otherMVC architectures. These frameworks are built based on top of the JSP/Servlettechnologies.Many web application frameworks are available (more than 30)JSF can be considered as web application frameworks in Java EEspecification. It’s better considered as a server-side component framework.JSF can be used to write applications that are not web based But mainly used for web applicationsJSF application consists of a series of XHTML pages containingcustom JSF tags, one or more JSF managed beans, optionalconfiguration file named faces-config.xml42

JSF (2) JavaServer Faces technology consists of the following: An API for representing components and managing their statehandling events, server-side validation, and data conversiondefining page navigationsupporting internationalization and accessibilityproviding extensibility for all these featuresTag libraries for adding components to web pages and forconnecting components to server-side objects5JSF (3) FacesServlet is a servlet that manages the request processing lifecycle for webapplications that are utilizing JSFs to construct the user interface.JSF Code can be reused and extended for components through the templating andcomposite component features. By JSF Annotations, you can automatically register the managed bean asa resource available for JSF applications. Implicit navigation rules allow developers to quickly configure pagenavigation (via faces-config.xml). JSF technology provides a rich architecture for managing componentstate, processing component data, validating user input, and handlingevents.63

Client Server Interaction in JSF Application The web page, myfacelet.xhtml, is built using JavaServer Faces component tags.Component tags are used to add components to the view (represented by myUI in thediagram), which is the server-side representation of the page.In addition to components, the web page can also reference objects, such as thefollowing: Any event listeners, validators, and converters that are registered on thecomponentsThe JavaBeans components that capture the data and process the applicationspecific functionality of the components7JSF vs JSP/Servlet MVC A fair comparison is to look at the use of the JSF framework vs.the use of MVC with servlets and JSP84

A Quick Review of Standard MVC (JSP/Servlet)HTML or JSPJava Code(Business Logic)Results(beans)Formsubmit form(Form ACTION matchesurl-pattern of servlet)Servlet(Store beans in request,session, or application mer);JSP1JSP2JSP3(Extract data from beansand put in output) {customer.firstName}9Advantages of JSF vs. Standard MVC (1) Custom GUI controls JSF provides a set of APIs and associated custom tags to createHTML forms that have complex interfaces There are many extra-rich third-party JSF librariesEvent handling JSF makes it easy to designate Java code that is invoked whenforms are submitted. The code can respond to particular buttons,changes in particular values, certain user selections, and so on.Managed beans In JSP, you can automatically populate a bean based on requestparameters. JSF extends this capability and adds in severalutilities, all of which serve to greatly simplify request paramprocessing.Integrated Ajax support You can use jQuery, Dojo, or Ext-JS with servlets and JSP.However, JSF lets you use Ajax without explicit JavaScriptprogramming and with very simple tags.105

Advantages of JSF vs. Standard MVC (2) Form field conversion and validation Page templating JSF has builtin capabilities for checking that form valuesare in the required format and for converting fromstrings to various other data types. If values are missingor in an improper format, the form can be automaticallyredisplayed with error messages and with the previouslyentered values maintained.Although JSP has jsp:include for reuse of content andjspf, JSF has a full-fledged page templating system thatlets you build pages that share layout or contentConsistent approach JSF encourages consistent use of MVC throughoutyour application.11Disadvantages of JSF vs. Standard MVC (1) Bigger learning curve To use MVC with the standard RequestDispatcher, you need to becomfortable with the standard JSP and servlet APIs. To use MVCwith JSF, you have to be comfortable with the servlet API and alarge and elaborate framework that is almost equal in size to thecore system.Similarly, if you have an existing app and want to add in somesmall amounts of Ajax functionality, it is moderately easy withjQuery (quite easy if you know JavaScript already). Switchingyour app to JSF 2.0 is a big investment.Worse documentation Compared to the standard servlet and JSP APIs, JSF has feweronline resources, and many developers find the online JSFdocumentation confusing and often poorly organized.126

Disadvantages of JSF vs. Standard MVC (2) Less transparent With JSF applications, there is a lot more going on behind thescenes than with normal JSP/Servlet Web applications. As aresult, JSF applications are: Harder to understandHarder to benchmark and optimizeRigid approach The flip side of the benefit that JSF encourages a consistentapproach to MVC is that JSF makes it difficult to use otherapproaches.13JSF example (hello.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 title Hello World /title /h:head h:body h3 Hello World Example - hello.xhtml /h3 h:form h:inputText value "#{helloBean.name}" /h:inputText h:commandButton value "Welcome Me" action "welcome" /h:commandButton /h:form /h:body /html you can put the page name directly inthe button’s “action” attribute. Forsimple navigation, it’s more thanenough, but, for complex navigation,you need to use the “navigation rule” in“faces-config.xml“.hello.xhtml – Renders a JSF text box and link itwith the “helloBean” (JSF managed bean),“name” property, and also a button to displaythe “welcome.xhtml” page when it’s clicked.147

welcome.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 title Hello World /title /h:head h:body bgcolor "white" h3 Hello World Example - welcome.xhtml /h3 h4 Welcome #{helloBean.name} /h4 /h:body /html The #{ } indicate this is a JSF expression language (EL)#{helloBean.name}, when the page is submitted, JSF will find the“helloBean” and set the submitted textbox value viathe setName() method. When welcome.xhtml page is display, JSF willfind the same session “helloBean” again and display the name propertyvalue via the getName() method.15Managed HelloBeanimport javax.faces.bean.ManagedBean;import nScopedpublic class HelloBean {private String name;JSF managed bean, with a nameproperty to store user data.name property can be accessed froma JSF page.public String getName() {return name;}public void setName(String name) {this.name name;}}168

web.xml (1) !-- Change to "Production" when you are ready to deploy -- context-param param-name javax.faces.PROJECT STAGE /param-name param-value Development /param-value /context-param !-- Welcome page -- welcome-file-list welcome-file faces/hello.xhtml /welcome-file /welcome-file-list !-- JSF mapping -- servlet servlet-name Faces Servlet /servlet-name servlet-class javax.faces.webapp.FacesServlet /servlet-class load-on-startup 1 /load-on-startup /servlet 17web.xml (2) !-- Map these files with JSF -- servlet-mapping servlet-name Faces Servlet /servlet-name url-pattern /faces/* /url-pattern /servlet-mapping servlet-mapping servlet-name Faces Servlet /servlet-name url-pattern *.jsf /url-pattern /servlet-mapping servlet-mapping servlet-name Faces Servlet /servlet-name url-pattern *.faces /url-pattern /servlet-mapping servlet-mapping servlet-name Faces Servlet /servlet-name url-pattern *.xhtml /url-pattern /servlet-mapping /web-app 189

helloAjax.xhtml html xmlns "http://www.w3.org/1999/xhtml"xmlns:f "http://java.sun.com/jsf/core"In this example, it make the button Ajaxable.xmlns:h "http://java.sun.com/jsf/html" When the button is clicked, it will make an Ajaxrequest to the server instead of submitting the h:body whole form. h3 Ajax Hello World Example /h3 h:form h:inputText id "name" value "#{helloBean.name}" /h:inputText h:commandButton value "Welcome Me" f:ajax execute "name" render "output" / /h:commandButton h2 h:outputText id "output" value "#{helloBean.sayWelcome}" / /h2 /h:form /h:body In the f:ajax tag : /html execute ”name” – Indicate the form component with an Id of “name” will besent to the server for processing. For multiple components, just split it with aspace in between, e.g execute ”name anotherId anotherxxId”. In this case, itwill submit the text box value.render ”output” – After the Ajax request, it will refresh the component with anid of “output“. In this case, after the Ajax request is finished, it will refreshthe h:outputText edpublic class HelloBean {private String name;public String getName() {return name;}public void setName(String name) {this.name name;}public String getSayWelcome(){//check if null?if("".equals(name) name null){return "";}else{return "Ajax message : Welcome " name;}}}2010

Run helloAjaxWhen the button is clicked, it makes an Ajax request andpass the text box value to the server for processing. Afterthat, it refreshes the outputText component and displays thevalue via getSayWelcome() method, without any “pageflipping effect“.21Facelets Facelets is a powerful but lightweight page declaration language that isused to build JSF views using HTML style templates and to buildcomponent trees.Facelets features include the following: Use of XHTML for creating web pagesSupport for Facelets tag libraries in addition to JSF and JSTL tag librariesSupport for the Expression Language (EL) EL represents a union of the Els offered by JSF and JSP technologiesTemplating for components and pagesAdvantages of Facelets for large-scale development projects include thefollowing: Support for code reuse through templating and composite componentsFunctional extensibility of components and other server-side objectsthrough customizationFaster compilation timeCompile-time EL validationHigh-performance rendering2211

Tag Libraries Supported by FaceletsTag LibraryURIExampleContentsJavaServerFaces FaceletsTag Libraryhttp://java.sun.com/jsf/facel ui:etsPrefixui:componentui:insertTags for templatingJavaServerFaces HTMLTag Libraryhttp://java.sun.com/jsf/html h:h:headh:bodyh:outputTexth:inputTextJavaServer Facescomponent tags forallUIComponent objectsJavaServerhttp://java.sun.com/jsf/core f:Faces Core TagLibraryf:actionListenerf:attributeTags for JavaServer Facescustom actions that areindependent of anyparticular render kitJSTL Core TagLibraryc:forEachc:catchJSTL 1.2 Core Tagsfn:toUpperCasefn:toLowerCaseJSTL 1.2 Functions Tagshttp://java.sun.com/jsp/jstl/ c:coreJSTL Functions http://java.sun.com/jsp/jstl/f fn:Tag Libraryunctions23Java Server Faces (JSF)Expression Language2412

Expression Language (1) The EL is used by both JSF technology and JSP technology. The EL represents a union of the expression languages offered byJSF and JSP technologiesJSF uses the EL for the following functions: Deferred and immediate evaluation of expressionsThe ability to set as well as get dataThe ability to invoke methodsEL provides a way to use simple expressions to perform the followingtasks: Dynamically read application data stored in JavaBeans components,various data structures, and implicit objectsDynamically write data, such as user input into forms, to JavaBeanscomponentsInvoke arbitrary static and public methodsDynamically perform arithmetic operations25Expression Language (2) The EL is also used to specify the following kinds of expressions that a customtag attribute will accept: Immediate evaluation expressions or deferred evaluation expressions. Value expression or method expression A value expression references dataA method expression invokes a methodRvalue expression or lvalue expression An immediate evaluation expression is evaluated at once by the underlyingtechnology, such as JavaServer Faces.A deferred evaluation expression can be evaluated later by the underlyingtechnology using the EL.An rvalue expression can only read a value, whereas an lvalue expression canboth read and write that value to an external objectEL provides a pluggable API for resolving expressions so custom resolvers thatcan handle expressions not already supported by the EL can be implemented.2613

Expression Language (3) Example {customer.name} // immediate evaluation syntax#{customer.name} // deferred evaluation syntax The first expression accesses the name property, gets its value, adds the valueto the response, and gets rendered on the page.The same can happen with the second expression. However, the tag handler candefer the evaluation of this expression to a later time in the page lifecycle, ifthe technology using this tag allows.In the case of JSF technology, the second expression is evaluatedimmediately during an initial request for the page. In this case, this expression acts as an rvalue expression.During a postback request, this expression can be used to set the value ofthe name property with user input. In this case, the expression acts as an lvalueexpression.27Expression Language (4) Examples #{employee.firstName} h:inputText value "#{employee.firstName}"/ Call getFirstName on bean named employee. Output it.When form displayed, call getFirstName, and if non-empty, fill it in asinitial value of textfield.When form submitted, validate value and if it is OK, pass value to thesetFirstName method#{employee.addresses[0].zip} Call getAddresses on bean named employee (which should return anarray or list), then take first entry, then call getZip on that, thenoutput it2814

Testing of the EL: ExampleBean@ManagedBeanpublic class SimpleBean {private String[] colors { "red", "orange", "yellow" };public String getMessage() {return("Hello, World");}Test Page !DOCTYPE . html xmlns "http://www.w3.org/1999/xhtml"xmlns:h "http://java.sun.com/jsf/html" . ul li Message: #{simpleBean.message} /li li First color: #{simpleBean.colors[0]} /li /ul .public String[] getColors() {return(colors);}}29Outputting Simple Bean Properties Format #{varName.propertyName} h:outputText value "#{varName.propertyName}" / For new JSF 2.0 code, top version is usually used unless you needsome other attribute of h:outputText (e.g. “rendered”)Interpretation First, find varName Search for “varName” in all defined scopes, from most specific to mostgeneral (request, session, application, in that order for standard Webapp scopes). Then look in managed bean defs and instantiate if found.Call getPropertyName and output the result This must be a normal zero-arg accessor method. If boolean, name ofmethod could be isPropertyName3015

Bean Properties Example: Java Code@ManagedBean@ApplicationScopedpublic class TestBean1 {private Date creationTime new Date();private String greeting "Hello";public Date getCreationTime() {return(creationTime);}public String getGreeting() {return(greeting);}}public double getRandomNumber() {return(Math.random());}31Bean Properties Example: Facelets Code html xmlns "http://www.w3.org/1999/xhtml"xmlns:h "http://java.sun.com/jsf/html" h:head title Accessing Simple Bean Properties /title h:outputStylesheet name "css/styles.css"/ /h:head h:body table border "5" align "center" tr th class "title" Accessing Simple Bean Properties /th /tr /table p/ ul li Creation time: #{testBean1.creationTime} /li li Greeting: #{testBean1.greeting} /li li Random number: #{testBean1.randomNumber} /li /ul /h:body /html stBean1.creationTime}Greeting: #{testBean1.greeting}Random number: #{testBean1.randomNumber}3216

Bean Properties Example: Result33Nested Bean Properties Format #{var.prop1.prop2.prop3} h:outputText value "#{var.prop1.prop2.prop3}" / Interpretation First, find var Same as before. Look in existing scopes (narrowest to widest). Use iffound. If not found, look in managed bean defs and instantiate.Call getProp1 on beanCall getProp2 on result of getProp1Call getProp3 on result of getProp2 And then output the result3417

Nested Properties Example: Namepublic class Name {private String firstName, lastName;public Name(String firstName, String lastName) {this.firstName firstName;this.lastName lastName;}public String getFirstName() {return(firstName);}}public void setFirstName(String newFirstName) {firstName newFirstName;}.35Nested Properties Example: Companypublic class Company {private String companyName, business;public Company(String companyName, String business) {this.companyName companyName;this.business business;}public String getCompanyName() { return(companyName); }}public void setCompanyName(String newCompanyName) {companyName newCompanyName;}.3618

Nested Properties Example: Employeepublic class Employee {private Name name;private Company company;public Employee(Name name, Company company) {this.name name;this.company company;}public Name getName() { return(name); }public Company getCompany() { return(company); }.}37Nested Properties Example: Employee1@ManagedBeanpublic class Employee1 extends Employee {public Employee1() {super(new Name("Bob", "Schneider"),new Company("lehman.com","EE Consulting"));}}3819

Nested Properties Example: Facelets Code ul li Employee's first name:#{employee1.name.firstName} /li li Employee's last name:#{employee1.name.lastName} /li li Name of employee's company:#{employee1.company.companyName} /li li Business area of employee's company:#{employee1.company.business} /li /ul 39Nested Properties Example: Result4020

Three Uses of #{.} Expression Designating output value #{employee.address} or h:outputText value "#{employee.address}"/ When form initially displayed, means to prepopulate field.Call getAddress and put value in field if non-empty.Designating submitted value h:inputText value "#{employee.address}"/ Anytime accessed, means to output getAddress h:inputText value "#{employee.address}"/ When form submitted, designates where value stored.Pass textfield value to setAddress.Designating method call after submission h:commandButton value "Button Label"action "#{employee.processEmployee}"/ When form submitted, designates action handler. This is exact methodname, not a shorthand for it.41Getter vs. Setter Method Correspondence Example When displaying form h:inputText value "#{myBean.a.b.c.d}"/ Find or instantiate myBean. Call getA. Call getB on result. CallgetC on that result. Call getD on that result. If non-empty use asinitial value of textfield.When submitting form Find myBean (instantiate new version if in request scope). CallgetA. Call getB on result. Call getC on that result. Then passsubmitted value to the setD method of that result. Point: only final one becomes setter on submission.This assumes value passes validation.4221

Submitting Properties Example: Employeepublic class Employee {private Name name;private Company company; public String processEmpl

4 Client Server Interaction in JSF Application The web page, myfacelet.xhtml, is built using JavaServer Faces component tags. Component tags are used to add components to the view (represented by myUI in the diagr

Related Documents:

Nov 07, 2006 · Introducing Java Server Faces (JSF) to 4GL Developers Page 5 Before JSF It is difficult to see how far JSF has raised the bar for Java web application UIs without first being aware of the development experience (or lack of) that was the catalyst for the simpler UI component b

Building JavaServer Faces Applications 7 JSF – A Web Framework JSR 127 – JSF specification v1.1 JSF 1.2 in progress (JSR 252) JSP 2.1 (JSR 245) will align with JSF JSF spec lead was the Struts architect JavaServer Faces technology simplifies building user interfaces for JavaServer

JSF has nothing to do with JSP per se. JSF works with JSP through a JSP tag library bridge. However, the life cycle of JSF is very different from the life cycle of JSP. Facelets fits JSF much better than JSP because Facelets was designed with JSF in mind, whereas integrating JSF and JSP has

What is JSF? Java Server Faces Java specification for building component-based user interfaces for web applications. It gives you the tools to communicate with java backing beans. JSF has all the javascript behind the scenes, creates the endpoints from JSF managed beans, and wires it all together. Agility. D

JSF i About the Tutorial Java Server Faces (JSF) is a Java-based web application framework intended to simplify development integration of web-based user interfaces. JavaServer Faces is a standardized display technology, which was formalized in a specification through the Java Community Process.File Size: 1MB

JSF includes a set of predefined UI components, an event-driven programming model, and the ability to add third-party components. JSF is designed to be extensible, easy to use, and toolable. This refcard describes the JSF development process, standard JSF tags, the JSF expressi

java.io Input and output java.lang Language support java.math Arbitrary-precision numbers java.net Networking java.nio "New" (memory-mapped) I/O java.rmi Remote method invocations java.security Security support java.sql Database support java.text Internationalized formatting of text and numbers java.time Dates, time, duration, time zones, etc.

Java Version Java FAQs 2. Java Version 2.1 Used Java Version This is how you find your Java version: Start the Control Panel Java General About. 2.2 Checking Java Version Check Java version on https://www.java.com/de/download/installed.jsp. 2.3 Switching on Java Console Start Control Panel Java Advanced. The following window appears: