JAVA SERVER FACES (JSF

)
JAVA SERVER FACES ( not to be confused with JSP..JAVA SERVER PAGES), is the latest technolgy from JCP(Java Community Process). It is a technology that can be used instead of Struts or along with Struts,during the transition phase. In this three part tutorial, the author gives the salient features of the technology with a simple illustration. --------JAVA SERVER FACES is the equivalent of ASP.Net's web-forms technology, with something more in features and something less in elegance and ease. JSF 1.0 was released in March, 2004 & a maintenance release 1.1 in June, 2004. So, it is quite recent. It has the backing from all the big players in J2EE field, like SUN,IBM,ORACLE,WEBLOGIC,BORLAND & APACHE. Craig MacLanahan, employed in SUN and the main contributor behind Struts , is the lead architect of JSF. He maintains that JSF is a supporting technolgy for Struts and not necessarily a replacing technology. He himself has suggested a method of integrating Struts with JSF and getting the best of both worlds. ( As this tutorial presumes a foundation in Struts, readers will do well to refer to the tutorial on Struts in DeveloperIQ..Jan2005). However, many analysts and authors are of the opinion that JSF is a definite improvement over Struts.Thus, it may be expected that quite a few applications in Industry , presently using Struts may switch over to JSF in the near future. In a few special cases, combining both JSF & Struts may be attempted, in order to maintain backward compatibility, during the transition phase.What is worth noting is that, transition is inevitable. From the view-point of productivity, builder tools are preferred by the Industry. For example, though, we can build very elegant and powerful applications in ASP.net , by using only a text-editor , Industry prefers to use Visual Studio , because of the number of advanced features like 'Intelli-sense', class browser etc.Similarly, while a considerable number of programmers prefer to use nothing but JDK and related libraries with texteditors , however complex the code might be,equally numerous programmers prefer to use the visual tools like JBuilder, JDeveloper and IBM's WebSphere Studio. The only problem is that while JDK is a single entity and hopefully can be mastered, builder tools are numerous and one cannot be equally productive in all the tools. Thus, anyone , who makes extensive use of such tools in his work, gets habitually tied to that tool and becomes much less productive in another environment. And for students and jobseekers, this poses a problem , since, with all their proficiency is a particular builer-tool

like '(say) Eclipse, the employer may be a fan of some other tool such as 'JDeveloper'. Such a problem does not occur in Microsoft Visual Studio, because there is one and only Studio. But even in Microsoft IDE, there are possibilities for working in various types of projects. Even the VC++ studio, offers options for console mode,win32 apps,Wizard-based dialog mode, SDI , MDI etc.Thus , if we want, we can develop our program without using wizards and code-generators thereby greatly reducing the number of files and code-bloat. It is a moot point, how advisable it is to learn java programming through an IDE! Ultimately, we have JDeveloper Java, JBuilder Java, Eclipse Java ,IdeaJ Java and so on.The spam wars going on, in the web between the respective camps ,is testimony to this splintering! That said, Industry is not prepared to forego the enormous increase in productivity offered by these tools. Thus learners have to master atleast two or three leading Java-IDE environments besides the plain JDK, to feel at home in Industrial environment and trust their luck to land in a java shop that uses an IDE known to them! That pinpoints the necessity for standards.JSF is such a standard. JSF is a specification, to which big companies like Borland , WebLogic, Oracle, SUN etc can offer Studio like tools to enhance productivity. And , they have already adopted and introduced JSF in their tools. Added to this is the advantage that it comes from JCP and that settles the issue, for good! .Hence JSF is inescapable area of expertise for Java developers. Just as we can build asp.net pages by hand-coding, we can build JSF also by handcoding. But , the main advantage as perceived by many analysts is that JSF being a specification, it has created a common standard for Visual Builder tools for webapplication development in Java. As it is backed by all the big players, it is bound to gain momentum and universal acceptance quickly. The problems that are addressed by Struts are different from those addressed by JSF. Struts is a framework based on MVC and it provides a ready-made structure, the main advantage being, DECLARATIVE MANAGEMENT in two important files, namely, web.xml and struts-config.xml. Secondly, it provides the concept of form-beans and centralized flow through the Controller servlet and respective action classes. It separates the view (JSP) and the model (business logic).It has been widely adopted by the industry and has proved its worth. Why then, JSF? Unlike Struts, JSF is not a web-application framework but was intended primarily, to be a User-interface technology, for web-based applications. In this aspect, it is exactly like ASP.net's WebForms.However, it soon grew out of this constraint and overlapped with much functionality and architecture of Struts.

------Let us now consider a simple example. Let there be a form with two text boxes and a button. When the user types his name in text1 and clicks the button, it should appear in text2. In VB, we would have written, text2.text=text1.text Had this been a stand-alone Java program, the code would have been, text2.setText(text1.getText()); ------------------But how do we do this in a web-application? In desktop applications, the variables are readily available in the program's memory space. But in web applications, HTTP is used and it is state-less. So, we can only collect the data typed in text1, in the server-side. After this , we have to dynamically create the same gui as before and populate the two textboxes, in the client's browser,and send the button too! Struts solves this problem, by creating a form-bean ..It would be nice if java web-application developers are 'made to feel' that they are working in a Swing based Applet , instead of web-based html form with all its 'forgetfulness'!That is precisely the problem tackled by JSF. For all appearances, it is as if the program works as in desktop application, where when we click a button(ActionEvent), make a change in textbox(TextEvent),make a selection in combo(ItemEvent),there is a reaction at component level .Struts, for all its advanced features, lacks this, as it is a page-level technology. JSF , being a component-level technology , tries to mimic a desktop application.We can imagine that the form with all its controls and data is saved and sent back to the browser in ASP.net and JSF , whereas, in traditional ASP & jsp, is is only the data that is accepted by the webserver and the gui has to be dynamically created again!The 'component tree' is said to be sent to the server and sent back to the browser as a hidden data , from which the original gui is 're-created'. A comparison of a simple program in VB,ASP & ASP.net, would bring out this aspect clearly. Or if we prefer, we can think of a Java desktop program, JSP ( either plain,or MVC or Struts) and JSF.If we combine the features of VB & ASP, we get ASP.net. (we are

speaking here of how it 'appears' to the developer, and not as it is implemented!).Similarly, when we combine Desktop Java & Struts, we get JSF. Clearly then , JSF is an advance over Struts, with the added advantage of being an official JCP standard, unlike Struts. About ten years back(1995), users were captivated by the tremendous reach and ease of Web-based applications. They used to call those start-ups as 'click & barter' company in the place of 'brick & mortar' company. Even today, there are hugely successful e-commerce companies like Amazon.com. So, the web-based business model is here to stay and grow. There is no going back to narrow lan(e)s of pre-web days. But, as business grows, developers and users alike, want to have all the ease, color, variety and user-interaction of a desktop application like VB ,in a web-based form! Surprisingly, was it not offered by Java Applet, in its very first month? But, it was objected that the business logic was done by the applet in the client's browser and except for very simple applications, downloading all those heavy classes from the server into the client's browser is not at all a good solution. Later, Sun came out with Servlets solution, in which the business logic is executed either in web-server or in the next tier of application server(RMI-style).And it is possible to send data to the servlet , not through the html form but through an applet.(They used to call it Applet-Servlet Communication and Tunnel method). If that is the case, the rich user-interface of applets can be combined with the power of a servlet and since the applet is used only for attractive user-interface and quick userinteraction, there could be no objection. The client's machine need not have JDK installed. The applet can be downloaded from server. This approach had an added advantage too. By suitable relaxation of security policy, data can be extracted from the hard-disk of the user by the applet and sent to the servlet. Similarly, the result sent by the servlet to the applet can be stored in the user's hard disk.Thus, we can save the data in a textbox to the file in hard disk, elegantly.That is the power of Component approach over page approach. Though, the first wave of books and literature on Servlets (1999)always spoke about servlet-applet communication, it fell out of favor, possibly due to the rift between Microsoft and Sun for fear that the almost universal Internet Browser and even Netscape Navigator, did not implement JDK fully in those days. And Swing is not implemented in these browsers directly , even today. It is only by using Java plug-in from Sun, we can view Swing applets in browsers.In J2EE field, where innovations and changes are occuring almost every month, a timelag of half a decade is equivalent to 'anachronism'. There is not much use in connecting a servlet through a stand-alone frame. We cannot go about distributing the client-side classes to the users.Only if it could be downloaded from the server, it can serve a vast clientele.It is signigicant that the Applet technology has no

equivalent in Microsoft technologies, to this day! Applets do not get installed in the user's machine but if AciveX controls embedded in html were downloaded , they got registered in the Windows Registry. ActiveX Documents tried by Microsoft , were not html forms and so could not be a standard method. That is what led them to develop ASP.net web forms.(please refer to a tutorial on ASP.net in DeveloperIQ...Feb --2004).But, still, the web-form controls are not the same as windows-form controls. DataGrid of windows-forms in Dotnet and DataGrid in Web-forms , will show this difference.Thus, it would appear that if it were possible to ressurect the Applet-Servlet approach, it would be incomparable, in effect. Now that Sun & Microsoft have buried the hatchet and agreed to co-operate for the coming decade, it will not be too much to expect Microsoft to implement jdk fully in its browser, atleast so far as Swing GUI goes. If that happens, we can combine all the advanced gui features of Swing applets with the power of Servlets/JSP. . In the absence of response to this wish-list, the next best solution is to create controls in server-side and somehow send it to the browser, as html. That is what is being done by ASP.net & JSF. We just forget that we are working in web-browser! Instead of complex session-tracking, we have the concept of 'sticky controls'(ie) any data placed in controls, retains the value , even after being submitted to the web-server. Round trip to the server is inevitable in a web application. True! But, the technolgy should hide all that complexity and make the coder feel that he is developing a desktop application. This is the chief merit of ASP.net's WebForm and also that of JSF. How then does JSF differ from ASP.net? There is no concept of Declarative management in ASP.net, exactly matching that in JSF. But the plus point of ASP.net webforms is that naming of the tags is much like standard html tags ( or VB) and elegant, unlike the JSF tags.Many more comparisons could be made but the main thrust of this tutorial is getting acquainted with JSF and so such a comparative evaluation, will have to wait. It is well to remember that there is no place for Talibanism in Technology!Discerning observers can easily see how each camp is learning from the other and trying to do one better.That is how progress takes place. Just because, we said that JSF is primarily a GUI technology for web-applications, it should not be taken to mean that it does away with all that concern about MVC Architecture. That would have been a step back, after so much work that has been done to achieve separation of Model,Controller & View. Thus, JSF adopts quite a few features from Struts. For example, here also there is a central controller servlet , only, it is named Faces Servlet. Here also, we have, a configuaration-file like Struts-config.xml, but it is now faces-config.xml

Decalative navigation method also has been adopted. Just as in Struts, the code simply returns 'Success' or 'Failure' and the resulting forwarding is decided declaratively by Navigation rules in the xml file. Internationalization, Error messages, Validations, beans for holding data, model beans etc are all very much in the same style of Struts. We have custom tags in JSF too.( And these tags may not always be compatible with JSTL!). ... And many of these html tags had no equivalent in JSTL. There is overlapping functionality and nomenclature between JSF tags and Struts tags. While, Struts used JSP EL(Expression language), JSF uses JSF EL! Thus, JSF may be looked at as an 'improved' Struts . Many authors feel that JSF is easier to implement and richer in user-functionality,but Struts validation is said to be much better. However,things could improve in the coming months. While Struts is strongly tied to standard browsers, JSF caters to all kinds of emerging browsers like wap-browsers and wireless devices, just like ASP.net. As wireless is the emerging trend, this also is a progressive step in JSF.At the pace in which wireless communication infrastructure and technologies are being developed all over the world, purely desktop wizardry has no value atall, in future. The real challenge is to develop a web-application with the look and feel of the desktop application!It takes some effort to effect this change in approach. What JSF brings to the party is ,the direct Event model , like Swing's Action event and ActionListeners,a concept like Container for controls in Swing, etc. ( 'Mastering Java Server Faces' by Bill Dudney & others..Wiley/DreamTech.. makes a detailed comparative study of Swing/Struts/JSF approach and is instructive). In this second part of the tutorial, the author explains the practical steps to get our first few demos in JSF, running. Basic theory behind the steps also are given. We are using Tomcat-5 as the Web-server,along with JDK 1.4.2, for the following experimental work. First of all , we have to instal JSF package in our system.We downloaded JSF1.1 , from : http://java.sun.com/j2ee/javaserverfaces/download.html The jsf1_1.zip is round 10 MB and it takes about an hour to get downloaded . We unzip the file into f:\jsf Inside the jsf folder we will get 7 sub-folders: a) docs

b) javadocs c) lib d) metadata e) renderkitdocs f) samples g) tlddocs The samples folder is useful to get started. There are four sample demos in that folder as *.war files. i) jsf-cardemo.war

ii) jsf-components.war iii) jsf-guessNumber.war iv) jsf-nonjsp.war Of these four, jsf-gueessNumber demo has minimum features , and is best suited for getting a feel for the technology.So, we copied jsf-guessNumber.war to : 'e:\tomcat5\webapps' folder and restarted the Tomcat5 server. --------------------------->e:\tomcat5\bin >set JAVA_HOME=e:\jdk1.4.2 >startup ---------------------------The war file gets expanded automatically and we get the standard j2ee directory structure, inside the jsf-guessNumber folder in e:\tomcat5\webapps folder. ..\webapps\jsf-gussNumber\WEB-INF\classes ..\webapps\jsf-guessNumber\WEB-INF\lib

All the jar files needed for running the jsf program are present in , lib folder of WEB-INF. They are listed below: i) commons-beanutils.jar ii) commons-collections.jar iii) commons-digester.jar iv) commons-logging.jar v) jsf-api.jar vi) jsf-impl.jar vii) jstl.jar viii) standard.jar It is useful to note down these details so that we can easily follow the documentation , articles and books, later. Let us see the significance of these jar files now. ( refer to page: 118 of JSF by Dudney). 1)jsf-api.jar : contains the standard JSF API classes and interfaces that all JSF implementations must satisfy. 2) jsf-ri.jar : represents the Sun Reference implementation of JSF API. 3) jstl.jar & standard.jar contain the JSTL files. The Reference implementation is based on JSTL. 4) The commons*.jar files are used by the Sun Reference implemenation. 'commons' utilities are being mentioned by many experts as invaluable library for fast software development. It will be dealt with in detail in a forthcoming tutorial. We can now start the browser and type the URL as : 'http://localhost:8080/jsf-guessNumber/index.jsp' we will get textbox and a button along with the image of Sun's mascot, the 'Duke'..We will be asked to type a number between 0 & 10.If we type a character like 'a' and submit ,

we will get validation error message in red. If we type a 'wrong' guess, we are informed so. After a few trials, we get correct result. Nothing much. But,it shows that JSF is working in our system and we get ready to begin our experimenation.! The Struts application comes with struts-blank.war and it is renamed to our application name . It would have been better if the JSF distribution also came with such a skeleton application. But , there is no such demo and that is why we are using the guessNumber folder , so that we get the standard xml files, required for our application. If we type it from scratch, there will be typing errors and difficulties. The best thing is to rename jsfguessNumber folder as ,(say) 'ourdemo'. We now delete all the jsp files directly under 'ourdemo' folder.We delete all the class files under 'WEB-INF\classes' of 'ourdemo', because they are applicable to guessNumber app only.Retain all the jar files in lib folder under WEB-INF. There will be two jar files in WEB-INF folder. a) web.xml b) faces-config.xml We need not touch anything in web.xml file but we can modify the existing faces-config.xml as follows: ---------------------------------------// \webapps\ourdemo\WEB-INF\faces-config.xml

<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN" "http://java.sun.com/dtd/ web-facesconfig_1_1.dtd"> <faces-config> <application>

<locale-config> <default-locale>en</default-locale> </locale-config> </application> <navigation-rule> <description> </description> </navigation-rule> </faces-config> --------------------------------------------We should remember to restart the Tomcat server. Now we edit a simple jsp file and test. ----------------------------------//..tomcat5\weebapps\ourdemo\mathew.jsp <html> <body> I AM MATHEW <br> </body> </html> -------------------------------------If we type the URL as http://localhost:8080/ourdemo/mathew.jsp, we should get the result as :

'I AM MATHEW'. Thus 'ourdemo' app is working. ---We now create a simple JSF program to learn about the tag library of JSF. ----------------------// tomcat5\webapps\ourdemo\jsfgui.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <f:view> <html> <body <h:form <h:outputText <h:graphicImage </h:form> </body> </html> </f:view> -------------When we type the URL as : bgcolor="cyan"> id="form1" > value="how are you?"/> url="/nathan.gif" />

'http://localhost:8080/ourdemo/jsfgui.jsp', we should get label 'how are you?' & nathan.gif . ================================ But , we should learn something about two important xml files, before we proceed further. The first file that we have to study, is 'web.xml' file in : 'webapps\ourdemo\WEB-INF' folder.As we got this file from an already running example (ie)guessNumber, everything required to test our jsf will be in place.The web.xml file is given below. We need not type this. It would be already available. The file is given here, just to point out the important entries. This file was obtained by deleting comments and descriptions from the original web.xml file of guessNumber application, to serve as a model, to make it less cluttered. This basic model file can then be used for other applications. In all the applications, the web.xml file will be same! (just as the web.xml file was same in all the Struts examples). But we should carefully note that the name of the central controller servlet and its URL-pattern. --------------------------------------// ..\webapps\ourdemo\WEB-INF\web.xml

<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>trial</display-name> <description> </description> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name>

<param-value>client</param-value> </context-param> <context-param> <param-name>com.sun.faces.validateXml </param-name> <param-value>true</param-value> <description> </description> </context-param> <context-param> <param-name>com.sun.faces.verifyObjects</param-name> <param-value>true</param-value> <description> </description> </context-param> <!-- Faces Servlet --> <servlet> <servlet-name>Faces Servlet </servlet-name> <servlet-class>javax.faces.webapp.FacesServlet </servlet-class> <load-on-startup> 1 </load-on-startup> </servlet> <!-- Faces Servlet Mapping -->

<servlet-mapping> <servlet-name>Faces Servlet </servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file> faces/login.jsp </welcome-file> </welcome-file-list> </web-app> ============================================ In the servlet-mapping tag, we can make use of two styles of url-pattern. The first style is known as 'extension mapping'. ( example: *.jsf). The JSF specification recommends the use of 'faces' as the extension but we can also use *.jsf. The Faces Servlet automatically translates this name to a corresponding JSP. ---------------------------------------(EX) < http://localhost:8080/demo/index.jsf> or < http://localhost:8080/demo/index.faces> would be translated automatically as: <http://localhost:8080/demo/index.jsp>

---------------------------------------The second method of servlet-mapping is known as 'prefix mapping'. --------------------------------------(example) <url-pattern>/faces/*</url-pattern> In the web.xml file shown above, we are using 'prefix mapping'. (ex) http://localhost:8080/demo/faces/ will be sent to: http://localhost:8080/demo/faces/index.jsp =========================================== Another point to be noted is the detail about the STATE-SAVING-METHOD param. The state of the various controls can be saved either in the server-side or in the clientside. We have specified 'client' as the option. This is saved as 'viewstate'. If we have a sense of 'deja vu', it is because , the same technique is used in ASP.net too! --Next we should learn the basics of another important xml file . Just as we had the strutsconfig.xml file, here too we have faces-config.xml file. This file has the following child-elements: The order in which these elements occur is important and should be retained. 1) application: 2) factory: 3) component: 4) converter: 5) managed-bean

6) navigation-rule: 7) reference-bean: 8) render-kit: 9) lifecycle: 10) validator: ---For the usual applications, it is advisable to accept the defaults for most of these. Since 'zero' entries are permitted for all these child elements, we can just remove many of them. The items shown in 'bold' such as managed-bean, navigation-rule are the most needed items. However, for the jsfgui.jsp, these are not needed. So the skeleton faces-config.xml will appear as shown earlier to begin with. -------------------------------------------We are now ready to test jsfgui.jsp. Start the browser and type the URL as: 'http://localhost:8080/ourdemo/jsfgui.jsp' We will get , a label 'how are you' and nathan.gif. So, we are able to get started with the tags in JSF. The names of these tags are unfortunately , a bit contrived and confusing. JSF provides two tag libraries,as mentioned at the beginning of jsfgui.jsp. -------------------------------------------<%@ <%@ uri="http://java.sun.com/jsf/html" prefix="h" uri="http://java.sun.com/jsf/core" prefix="f" %> %>

------------------------------------------Inside the body tag, we must always provide <view> tag. This is very important. All jsf

tags are placed inside the <view> tags. The <view> tag provides a place for saving the state of the components tree before sending the response. If we have configured to save it in client, it is returned as 'hidden' viewstate , just as in ASP.net. We will now see a few jsf tags and the html equivalents. -----------------------------------------1) <h:form> 2) <h:outputText> is simply a means to output any string to the browser. 3) <h:inputText> 4) <h:commandButton> 5) <h:inputSecret> 6) <h:panelGrid> 7) <h:graphicImage> 8) <h:message> 9) <h:selectOneRadio> 10) <h:selectOneMenu> <radio> <select> type=text type=submit type=password table img <form>

11) <h:selectBooleanCheckbox> type=checkbox 12) <h:OutputLabel>a label for input field) 13) <h:outputLink> 14) <h:panelGroup 15) <h:message> 16) <h:selectManyCheckbox> similar to checkboxlist of asp.net 17) <h:inputTextArea> <textarea> hyperlink a groupbox

18) <h:inputHidden>

hidden

19) <h:selectManyListBox> multi-list select 20) <h:commandLink> an action link.

In this third part of tutorial on JSF, the author deals with important topics like 'backing beans',event-handling,validation etc. In attempting to understand a new technology, beginning with an overall perspective, what Bill McCarty would call 'Upper Management Perspective' is more important than the technical details. Next comes' hands-on experimentation'. And finally, we go into the details of practical implementation. While the first part of this tutorial dealt with the overall perspective and the need for JSF,the second part gave the practical steps required for installation, preliminary testing and basic trial for our own example.In this third part , we will have a deeper study of the essential ingredients of the JSF architecture ,backed up with simple illustration for each of those ingredients. In a nice but bulky book 'JSF IN ACTION', (Manning/DreamTech) published in Jan 2005, KITO MANN, has given an outline of the various component parts of the JSF, as follows. i) UI components & JSF Tag library ii) Navigation iii) Event-handling iv) BackingBeans & ManagedBeans config v) value-binding vi) method-binding vii) validation viii) converters ----------------------------------These will be the preliminary topics, followed by: 1) Security

2) tabular data 3) business layer & data tier 4) Internationalization --------------------------------------We have already seen the basics of JSF tags.In our next demo, we will study the details about 'Navigation'. This requires some suitable entries in faces-config.xml file. -- --------------------------------------//jsfevent.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <f:view> <html> <body <h:form bgcolor="cyan"> id="form1" > action="success" />

<h:commandButton value="mathew"

<h:commandButton value="amy" action="failure" /> </h:form> </body> </html> </f:view> --------------------------------------------// e:\tomcat5\webapps\ourdemo\mathew.jsp ( already available)

<html>

<body> I AM MATHEW </body> </html> -------------------------------------------// e:\tomcat5\webapps\ourdemo\amy.jsp

<html> <body> I AM AMY <br> </body> </html> -------------Now, we have to make the following entries in faces-config.xml // e:\tomcat5\webapps\ ourdemo\WEB-INF\faces-config.xml ( this is to be added to existing entries) <navigation-rule> <from-view-id> /jsfevent.jsp </from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/mathew.jsp</to-view-id> </navigation-case>

<navigation-case> <from-outcome>failure</from-outcome> <to-view-id>/amy.jsp</to-view-id> </navigation-case> </navigation-rule> -----------------------------------------and restart tomcat server -----------------------------------------Now, open IE and type the URL as 'http://localhost:8080/ourdemo/ faces/jsfgui.jsp' We will get just two buttons.One button will have the caption as 'mathew' and the other button's caption will be 'amy'. If we click button1,we will be taken to mathew.jsp and if we click button2 , we will be taken to amy.jsp, with corresponding displays. Thus, we have given a demo for action event as well as 'Declarative navigation'. We say,this is declarative navigation, because, the outcome of clicking 'button1' has not been hard-coded but simply mentioned as a string "success" in the button's action attribute. What this 'string' should do, has been indicated in the jsf-config.xml under navigation rule attributes., as shown below. ------<navigation-case> <from-outcome>success</from-outcome> <to-view-id>/mathew.jsp</to-view-id> </navigation-case> --------This is very much similar to the practice in Struts. Similarly, for button2 ( with caption 'amy'), the action attribute is 'failuree' and in the faces-config.xml, we have mapped it to 'amy.jsp'.

Hopefully, this illustration explains the method of action event, navigation rule syntax and princople of declarative navigation. ****************************************** Now, we take up the MOST IMPORTANT topic of BackingBean. Though the name is unique, it is just nothing but the standard javabean. Let us first create a bean 'player'. The procedure is as follows: f:\>md jsfexample f:\>cd jsfexample f:\jsfexample>md demo f:\jsfexample\demo\>edit player.java ( it may be noted that the name of the working folder NEED NOT BE the same name as the package name! Our working folder is 'demo' but the package name is ourdemo). ( The package name has nothing to do with the Application context name either, though it is followed by Sun demos.) --------------------------------------// f:\jsfexample\demo\>player.java package ourdemo; import javax.faces.context.*; import javax.faces.component.*; import javax.faces.validator.*; public class player { String String firstname; lastname;

public void {

setfirstname(String a)

firstname=a; } public { return firstname; } //---------public void { lastname=b; } public String { return lastname; } //------------------public void changeName() { lastname= firstname+" "+lastname; } } getlastname() setlastname(String b) String getfirstname()

==== Now set path for the current folder. f:\jsfexample\demo> set path=c:\windows\command;e:=\jdk1.4.2\bin set classpath for the folder as: demo>set classpath=j:\jsfexample; f:\jsf11\lib\jsf-api.jar ( to be typed in a continuous line). --------Now, we will be able to compile without any problem. \demo>javac player.java The player.class file thus obtained must be copied to 'ourdemo' folder under : e:\tomcat5\webapps\ourdemo\WEB-INF\classes ----edit \webapps\ourdemo\jsfmbean.jsp //' jsf-managedbean' demo

----------------------------------------//jsfmbean.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<f:view> <html> <body bgcolor="cyan">

<h:form id="form1" > <h:inputText id="text1" value="#{text2}" /> <h:inputText id="text2" value="#{player.lastname}" /> <h:commandButton action="success" value="success" /> <h:commandButton action="#{player.changeName}" value="failure" /> </h:form> </body> </html> </f:view> ============================================= Add the following entry to faces-config.xml <navigation-rule> <from-view-id>/jsfmbean.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/mathew.jsp</to-view-id> </navigation-case> </navigation-rule> <managed-bean> <managed-bean-name>player</managed-bean-name>

<managed-bean-class> ourdemo.player </managed-bean-class> <managed-bean-scope> session </managed-bean-scope> <managed-property> <property-name>firstname</property-name> <value>Mahathma</value> </managed-property> <managed-property> <property-name>lastname</property-name> <value>Gandhiji</value> </managed-property> </managed-bean> ============== Open IE and type the URL as ; http://localhost:8080/ourdemo/faces/jsfmbean.jsp --------------------------------------We will get two textboxes and two buttons. We will get the value 'Gandhiji' bound in the second textbox.There will be no entry in text1; This is known as 'Value Binding'. What do we mean by that? As we know, the player bean class has two attributes namely, 'first name ' and 'last name'. We have specified in the jsf-config.xml file the init value for these two attributes. In the jsp sheet we have mentioned that the value of text2 is "#{player.lastname}".

This is known as JSF EXPRESSION LANGUAGE . (This is very much similar to JSP EL. But, it is not totally compatible with JST EL). Thus the value of the bean is bound to text2. This is a two-way process. Hereafter, if either the bean's attribute is changed by code or by the user changing the value in the screen, the inner vvalue is changed, each time the page is submitted. The value is retained ( sticky) so long as the page's session is maintained. This is a very important feature and almost the most important feature in JSF. --------------------------------------------There is another method of binding also. This is very unique in JSF, not found in Struts. This is known as 'method binding'. Our player bean has a method known as 'changeName'. When the button 'success' is clicked we will be transfered to mathew.jsp. When the button 'failure' is clicked we will get 'Mahathma Gandhiji' in textbox2. This is an example for method binding. This result is obtained from the 'changeName' method of the bean. --------------------------------------Next we will move on to another important part(ie) 'Validation'. JSF provides three standard validator classes 1.DoubleRange Validator JSF Tag : validateDoubleRange This tag validates whether the submited value lies in the specified floating point range. A minimum value, a maximum value or both may be specified. 2.Length Validator JSF Tag : validateLength This tag validates the length of the submitted string value and that its length is within the supplied minimum and maximum values. 3.LongRange Validator JSF Tag : validateLongRange This tag validates whether the submitted value can be converted to a long and that it is within the supplied minimum and maximum values.

Now we will see an example for standard validation. -------------------------------------//jsfvalidation.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <f:view> <html> <body bgcolor="cyan">

<h:form id="form1" > <h:outputText value="Enter name not more than 5 chars" /> <br> <h:inputText id="text1" required="true" value="" > <f:validateLength </h:inputText> <h:message style="color:red" for="text1" /><br> <h:outputText value="Enter number between 1000 and 99999"/><br> <h:inputText id="text2" required="true" value="" > <f:validateLongRange minimum="1000" maximum="99999" /> </h:inputText> <h:message style="color:red" for="text2" /> <br> maximum="5" />

<h:outputText value="Enter number between 1.000 and 9999.999"/><br> <h:inputText id="text3" required="true" value="" > <f:validateDoubleRange minimum="1.000" </h:inputText> <h:message style="color:red" for="text3" /> <br><br> <h:commandButton value="Click Me" /> </h:form> </body> </html> </f:view> --------Open IE and type the URL as http://localhost:8080/ourdemo/faces/jspvalidation.jsp We will get three labels and three textboxes. Type the value 'sam' in textbox1, 10000 in textbox2 and 19.99 in textbox3 and click the button 'Click Me'. We won't get any error message.When the button is clicked, the page is submitted to the server. When we leave any textbox empty, we'll get the error message as 'value is required'. Type the value 'thomas' in textbox1 and click submit. We will get the error message 'value is greater than allowable maximum of '5''. When we type some characters in textbox2 and textbox3, we will get the error message as 'value is of the correct type '. When we type the numbers out of range in textbox2 and textbox3, we will get the error message 'Specified attribute is not between the expected values'. We shall see the other topics of JSF in the next installment. ******************************************* Reference Books: 1.Java server faces in action - Kito D.Mann (Manning/DreamTech (2005 jan). maximum="9999.999" />

2.Java server faces - Hans Bergsten (SPD/OReilly/june 2004) 3.Mastering Java server faces - Bill Dudney ( Wiley/DreamTech/2004) ***************************************

Sign up to vote on this title
UsefulNot useful