SlideShare a Scribd company logo
1 of 15
First step with JavaServer Faces using Eclipse
This tutorial facilitates the first steps with the quite new framework JavaServer Faces (JSF). Step
by step an example application (a library) will be created, which illustrate the different elements of
the framework.
The example application will provide the following functionality.
•   Display a book overview (list of books)
•   Add, edit and delete a book

Generals
Author:
Sascha Wolski
http://www.laliluna.de/tutorials.html Tutorials for Struts, EJB, xdoclet, JSF, JSP and eclipse.
Date:
December, 21 2004

Source code:
The sources do not contain any project files of eclipse or libraries. Create a new project following
the tutorial, add the libraries as explained in the tutorial and then you can copy the sources in your
new project.
http://www.laliluna.de/assets/tutorials/first-java-server-faces-tutorial.zip
PDF Version des Tutorials:
http://www.laliluna.de/assets/tutorials/first-java-server-faces-tutorial-en.pdf
Development Tools
Eclipse 3.x
MyEclipse plugin 3.8
(A cheap and quite powerful Extension to Eclipse to develop Web Applications and EJB (J2EE)
Applications. I think that there is a test version availalable at MyEclipse.)

Application Server
Jboss 3.2.5
You may use Tomcat here if you like.




Create a JavaServer faces project
Create a new web project. File > New > Project.
Set a nice name and add the JSTL Libraries to the project.
Add the JavaServer faces Capabilities. Right click on the project and choose MyEclipse > Add
JSF Capabilities.
The class Book
Add an new package de.laliluna.tutorial.library und create a new class named Book.




Open the class and add the following private properties:
•   id
•   author
•   title
•   available
Generate a getter- and setter-method for each property. Right click on the editor window and
choose Source > Generate Getter- and Setter Methods.




Furthermore you have to add a constructor, which set the properties if you initialisize the instance
variable of the newly object.
The following source code show the class book.
public class Book implements Serializable {

       //    ------------------ Properties            --------------------------------
       private long id;
       private String author;
       private String title;
       private boolean available;

       //    ------------------ Constructors --------------------------------
       public Book(){}
       public Book(long id, String author, String title, boolean available){
             this.id = id;
             this.author = author;
             this.title = title;
             this.available = available;
       }

       //     ------------------ Getter and setter methods ---------------------

       public String getAuthor() {
             return author;
       }
       public void setAuthor(String author) {
this.author = author;
       }
       public boolean isAvailable() {
             return available;
       }
       public void setAvailable(boolean available) {
             this.available = available;
       }
       public long getId() {
             return id;
       }
       public void setId(long id) {
             this.id = id;
       }
       public String getTitle() {
             return title;
       }
       public void setTitle(String title) {
             this.title = title;
       }
}


Add a getter and setter for the class.
/**
  * Set the properties
  * @param book
  */
public void setBook(Book book){
       this.setId(book.getId());
       this.setAuthor(book.getAuthor());
       this.setTitle(book.getTitle());
       this.setAvailable(book.isAvailable());
}

/**
 * @return book object
 */
public Book getBook(){

       return new Book(this.getId(),
                         this.getAuthor(),
                         this.getTitle(),
                         this.isAvailable());
}



The database class
We use a class to provide some test data without using a database. Download the sample
application of this tutorial and copy the class SimulateDB.java find in the folder
src/de/laliluna/tutorial/library/ in the package
de.laliluna.tutorial.library.

The class BookList
Create a futher class BookList in the package de.laliluna.library. This class inlcudes the
property books, which represent the list of books. Generate a getter- and seter-method for the
property books and change the getter-method like the following.
public class BookList {

       // ------------------------- Properties ---------------------------
       Collection books;

       // ------------------------- Getter and Setter --------------------
/**
         * @return collection of books
         */
        public Collection getBooks(){

                  SimulateDB simulateDB = new SimulateDB();

            /* Holt sich die Session auf dem Externen Context
             */
            Map session = FacesContext.getCurrentInstance().getExternalContext
().getSessionMap();

                  /* Lies alle Bücher auf der simulierten Datenbank aus
                   */
                  books = simulateDB.getAllBooks(session);

                  return books;
        }

        /**
          * @param books The books to set.
          */
        public void setBooks(Collection books) {
               this.books = books;
        }
}


Your package explorer will look like the picture below.




Action listener methods
To provide that a user can add, edit or delete a book, we have to include the appropriate
functionality. This functionality will be implemented in action listener methods / classes. If an event
occur (ex.: a user clicks on a link) an action listener method / class will be called and processed.
Open the class Book and add four methods , which process the following functionality.
•   Initializise a book
•   Edit a book
•   Save a book
•   Delete a book
Initialize a book
/**
 * Initial the properties of the class with null
 * @param event
 */
public void initBook(ActionEvent event){

      /*
       * init the book object
       */
      this.setBook(new Book());
}


Edit a book
/**
 * Get the book to edit and assign it to the bean
 *
 * @param event
 */
public void selectBook(ActionEvent event){

      SimulateDB simulateDB = new SimulateDB();

      /*
       * Get the session map of the external context
       */
      Map session = FacesContext.getCurrentInstance().getExternalContext().
getSessionMap();

      /*
       * Find the UIParameter component by expression
       */
      UIParameter component = (UIParameter) event.getComponent().findComponent
("editId");

      /*
       * parse the value of the UIParameter component
       */
      long id = Long.parseLong(component.getValue().toString());

      /*
       * get the book by id and set it in the local property
       */
      this.setBook(simulateDB.loadBookById(id, session));
}


Save a book
/**
 * Add or update the book in the simulated database.
 * If the book id is not set the book will be added
 * otherwise the book will be updated
 *
 * @param event
 */
public void saveBook(ActionEvent event){

      SimulateDB simulateDB = new SimulateDB();

      /*
       * Get the session map of the external context
       */
      Map session = FacesContext.getCurrentInstance().getExternalContext().
getSessionMap();
/*
      * Add or update the book in the simulated database
      */
     simulateDB.saveToDB(this.getBook(), session);
}


Delete a book
/**
 * Delete a book in the simulated database
 *
 * @param event
 */
public void deleteBook(ActionEvent event){

     SimulateDB simulateDB = new SimulateDB();

      /*
       * Get the session map of the external context
       */
      Map session = FacesContext.getCurrentInstance().getExternalContext().
getSessionMap();

      /*
       * Find the UIParameter component by expression
       */
      UIParameter component = (UIParameter) event.getComponent().findComponent
("deleteId");

     /*
      * parse the value of the UIParameter component
      */
     long id = Long.parseLong(component.getValue().toString());

     /*
      * delete the book by id
      */
     simulateDB.deleteBookById(id, session);
}
The file faces-config.xml
The faces-config.xml is the central configuration file of JavaServer faces. In this file you define the
workflow of the application (on which action which site will be processed) , the managed bean
classes by JSF and something more.
The workflow of the library application looks like the following.




We define a navigation rule for this workflow.
Open the file faces-config.xml and add the following configuration.
<faces-config>

       <!-- Navigation rules -->
       <navigation-rule>
             <description>List of books</description>
             <from-view-id>/listBooks.jsp</from-view-id>
             <navigation-case>
                   <from-outcome>editBook</from-outcome>
                   <to-view-id>/editBook.jsp</to-view-id>
             </navigation-case>
       </navigation-rule>

      <navigation-rule>
            <description>Add or edit a book</description>
            <from-view-id>/editBook.jsp</from-view-id>
            <navigation-case>
                  <from-outcome>listBooks</from-outcome>
                  <to-view-id>/listBooks.jsp</to-view-id>
                  <redirect/>
            </navigation-case>
      </navigation-rule>
</faces-config>

<navigation-rule>
Define a navigation rule
<from-view-id>/listBooks.jsp</from-view-id>
Define the jsp file for which the containing navigation rule is relevant.
<navigation-case>
Define a navigation case
<from-outcome>editBook</from-outcome>
Define a name for this navigation case
<to-view-id>/listBooks.jsp</to-view-id>
Refers to the setted JSP File
<redirect/>
All parameters saved in the request will be losed when you set this tag.
If you want to access the bean classes in your JSP files, you have to register the bean classes in
faces-config.xml
Add the following source code.
<!-- Managed beans -->
<managed-bean>
      <description>
            Book bean
      </description>
      <managed-bean-name>bookBean</managed-bean-name>
      <managed-bean-class>de.laliluna.tutorial.library.Book</managed-bean-class>
      <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

<managed-bean>
      <description>
            BookList Bean
      </description>
      <managed-bean-name>bookListBean</managed-bean-name>
      <managed-bean-class>de.laliluna.tutorial.library.BookList</managed-bean-
class>
      <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

<managed-bean>
Define a managed bean
<managed-bean-name>bookBean</managed-bean-name>
Define a name for the managed bean. This name is used in the JSP file.
<managed-bean-class>de.laliluna.tutorial.library.Book</managed-bean-class>
Define the class which represent the bean.
<managed-bean-scope>request</managed-bean-scope>
Define in which scope the bean is saved.

Create the JSP files
In the first step we create a JSP file named index.jsp, which forwards the user to the list of
books.

index.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
    <jsp:forward page="/listBooks.faces" />
  </body>
</html>


In the second step we create the book overview.

listBooks.jsp
<%@ page language="java" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()
+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
      <base href="<%=basePath%>">

      <title>List of books</title>
</head>

<body>
      <f:view>
            <h:form id="bookList">
            <h:dataTable id="books"
                               value="#{bookListBean.books}"
                               var="book"
                               border="1">
              <h:column>
                <f:facet name="header">
                 <h:outputText value="Author"/>
                </f:facet>
                <h:outputText value="#{book.author}" />
              </h:column>
              <h:column>
                <f:facet name="header">
                  <h:outputText value="Title"/>
                </f:facet>
                <h:outputText value="#{book.title}" />
              </h:column>
              <h:column>
                <f:facet name="header">
                  <h:outputText value="Available"/>
                </f:facet>
                <h:selectBooleanCheckbox disabled="true"
                                                 value="#{book.available}" />
              </h:column>
              <h:column>
                <f:facet name="header">
                  <h:outputText value="Edit"/>
                </f:facet>
                <h:commandLink id="Edit"
                                 action="editBook"
                                 actionListener="#{bookBean.selectBook}">
                  <h:outputText value="Edit" />
                  <f:param id="editId"
                               name="id"
                               value="#{book.id}" />
                </h:commandLink>
              </h:column>
               <h:column>
                <f:facet name="header">
                  <h:outputText value="Delete"/>
                </f:facet>
                <h:commandLink id="Delete"
                                 action="listBooks"
                                 actionListener="#{bookBean.deleteBook}">
                  <h:outputText value="Delete" />
                  <f:param id="deleteId"
                               name="id"
                               value="#{book.id}" />
                </h:commandLink>
              </h:column>
            </h:dataTable>

            <h:commandLink id="Add"
                                 action="editBook"
                                 actionListener="#{bookBean.initBook}">
                  <h:outputText value="Add a book" />
            </h:commandLink>
            </h:form>
      </f:view>
</body>
</html>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
With directive taglib we include the JSF tag libraries
<f:view>
Renders a view component. All others tags must be included within this tag.
<h:form id="bookList">
Renders a HTML form.
<h:dataTable id="books" value="#{bookListBean.books}" var="book" border="1">
Renders a HTML table. The tag is used to loop over a list of data like a for loop. The parameter
value assign a list of data, in our case the list of books of the library. With the parameter var you
define the variable used to access a element (a book) of the list within the tag (loop).
<h:column>
    <f:facet name="header">
          <h:outputText value="Author"/>
    </f:facet>
    <h:outputText value="#{book.author}" />
</h:column>
Renders a column with a column header.
<f:facet name="header"> display the header.
<h:outputText value="Author"/> print out a header label.
<h:outputText value="#{book.author}" /> refers to the property author of the current
element of the list.
<h:commandLink id="Edit"
               action="editBook"
               actionListener="#{bookBean.selectBook}">
Renders a HTML link, which submits the form. The parameter action define the navigation case,
which is processed, after the form submits In our case the navigation case editBook, we have
added befor in the faces-config.xml, will be processed. We assign the action listener method to the
link with the parameter actionListener. After the user submit the form the method will be
processed.


The last JSP file includes a form to add and edit a book.

editBook.jsp
<%@ page language="java" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()
+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
      <base href="<%=basePath%>">

      <title>Add / Edit a book</title>
</head>

<body>
      <f:view>
            <h:form>
            <h:inputHidden id="id" value="#{bookBean.id}"/>
<h:panelGrid columns="2" border="1">

                     <h:outputText value="Author:" />
                     <h:inputText id="author"
                                  value="#{bookBean.author}">
                     </h:inputText>

                     <h:outputText value="Title:" />
                     <h:inputText id="title"
                                  value="#{bookBean.title}">
                     </h:inputText>

                     <h:outputText value="Available:" />
                     <h:selectBooleanCheckbox id="available"
                                              value="#{bookBean.available}" />

              </h:panelGrid>

            <h:commandButton value="Save"
                                     action="listBooks"
                                     actionListener="#{bookBean.saveBook}" />
            </h:form>
      </f:view>
</body>
</html>

<h:inputHidden id="id" value="#{bookBean.id}"/>
Renders a HTML hidden element. Value refers to the managed bean bookBean and its property
id, which indicated in the faces-config.xml.
<h:panelGrid columns="2" border="1">
Renders a HTML table with two columns.
<h:inputText id="author" value="#{bookBean.author}">
Renders a HTML text field. Value refers to the property author of our class Book.
<h:commandButton value="Save"
                     action="listBooks"
                     actionListener="#{bookBean.saveBook}" />
Renders a HTML submit button with the value save and the action listBooks. The action listener
method saveBook will be processed if the user submit the form.



Test the application
Start the jboss and deploy the project as Packaged Archive.




Call the project now http://localhost:8080/LibraryWeb/

More Related Content

What's hot

Simplifying JavaScript Projects with ReactJS
Simplifying JavaScript Projects with ReactJSSimplifying JavaScript Projects with ReactJS
Simplifying JavaScript Projects with ReactJSKevin Dangoor
 
The state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinThe state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinNida Ismail Shah
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreNicolas Carlo
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowkatbailey
 
Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Nida Ismail Shah
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)Jeff Eaton
 
Firebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroesFirebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroesPeter Friese
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupalBlackCatWeb
 
Writing Drupal 5 Module
Writing Drupal 5 ModuleWriting Drupal 5 Module
Writing Drupal 5 ModuleSammy Fung
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011Maurizio Pelizzone
 
Drupal Development
Drupal DevelopmentDrupal Development
Drupal DevelopmentJeff Eaton
 
Intoduction on Playframework
Intoduction on PlayframeworkIntoduction on Playframework
Intoduction on PlayframeworkKnoldus Inc.
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashBret Little
 

What's hot (18)

Simplifying JavaScript Projects with ReactJS
Simplifying JavaScript Projects with ReactJSSimplifying JavaScript Projects with ReactJS
Simplifying JavaScript Projects with ReactJS
 
Metaworks3
Metaworks3Metaworks3
Metaworks3
 
The state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinThe state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon Dublin
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Hooks and Events in Drupal 8
Hooks and Events in Drupal 8
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
 
Firebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroesFirebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroes
 
Lodash js
Lodash jsLodash js
Lodash js
 
Doctrine for NoSQL
Doctrine for NoSQLDoctrine for NoSQL
Doctrine for NoSQL
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
 
Sequelize
SequelizeSequelize
Sequelize
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupal
 
Writing Drupal 5 Module
Writing Drupal 5 ModuleWriting Drupal 5 Module
Writing Drupal 5 Module
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011
 
Drupal Development
Drupal DevelopmentDrupal Development
Drupal Development
 
Intoduction on Playframework
Intoduction on PlayframeworkIntoduction on Playframework
Intoduction on Playframework
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 

Viewers also liked

Apresentação Rapida Sicod
 Apresentação Rapida Sicod Apresentação Rapida Sicod
Apresentação Rapida SicodNilson Santos
 
P'ti mag - 23.10.15
P'ti mag - 23.10.15P'ti mag - 23.10.15
P'ti mag - 23.10.15Marsatwork
 
ISO lead auditor
ISO lead auditorISO lead auditor
ISO lead auditorMina Karam
 
P'ti mag - 22.01.16
P'ti mag - 22.01.16P'ti mag - 22.01.16
P'ti mag - 22.01.16Marsatwork
 
Why i chose the music videos
Why i chose the music videosWhy i chose the music videos
Why i chose the music videoskfirza
 
Variables aleatorias
Variables aleatoriasVariables aleatorias
Variables aleatoriasKarla Eriana
 
Pharmacological Management of Pain In The Dental Care
Pharmacological Management of Pain In The Dental CarePharmacological Management of Pain In The Dental Care
Pharmacological Management of Pain In The Dental CareCharles Sharkey
 
E commerce under GST
E commerce under GSTE commerce under GST
E commerce under GSTGST Law India
 
Precautions in GST for Construction / Project Sector
Precautions in GST for Construction / Project SectorPrecautions in GST for Construction / Project Sector
Precautions in GST for Construction / Project Sectorsandesh mundra
 
Ulcerative lesions
Ulcerative lesionsUlcerative lesions
Ulcerative lesionsmemoalawad
 

Viewers also liked (16)

Pasted image-1739
Pasted image-1739Pasted image-1739
Pasted image-1739
 
Tiras comicas 3ºa
Tiras comicas 3ºaTiras comicas 3ºa
Tiras comicas 3ºa
 
Apresentação Rapida Sicod
 Apresentação Rapida Sicod Apresentação Rapida Sicod
Apresentação Rapida Sicod
 
Rezhim dhq shkolnika
Rezhim dhq shkolnikaRezhim dhq shkolnika
Rezhim dhq shkolnika
 
P'ti mag - 23.10.15
P'ti mag - 23.10.15P'ti mag - 23.10.15
P'ti mag - 23.10.15
 
ISO lead auditor
ISO lead auditorISO lead auditor
ISO lead auditor
 
Presentacion 1 ca3 7
Presentacion 1 ca3 7Presentacion 1 ca3 7
Presentacion 1 ca3 7
 
P'ti mag - 22.01.16
P'ti mag - 22.01.16P'ti mag - 22.01.16
P'ti mag - 22.01.16
 
Why i chose the music videos
Why i chose the music videosWhy i chose the music videos
Why i chose the music videos
 
Igualdad de Género.
Igualdad de Género.Igualdad de Género.
Igualdad de Género.
 
Variables aleatorias
Variables aleatoriasVariables aleatorias
Variables aleatorias
 
Pharmacological Management of Pain In The Dental Care
Pharmacological Management of Pain In The Dental CarePharmacological Management of Pain In The Dental Care
Pharmacological Management of Pain In The Dental Care
 
E commerce under GST
E commerce under GSTE commerce under GST
E commerce under GST
 
Precautions in GST for Construction / Project Sector
Precautions in GST for Construction / Project SectorPrecautions in GST for Construction / Project Sector
Precautions in GST for Construction / Project Sector
 
Ulcerative lesions
Ulcerative lesionsUlcerative lesions
Ulcerative lesions
 
Bianco toro
Bianco toroBianco toro
Bianco toro
 

Similar to First java-server-faces-tutorial-en

Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Link.javaLink.javapackage com.bookstore.domain.model;import .docx
Link.javaLink.javapackage com.bookstore.domain.model;import .docxLink.javaLink.javapackage com.bookstore.domain.model;import .docx
Link.javaLink.javapackage com.bookstore.domain.model;import .docxSHIVA101531
 
Library Project Marcelo Salvador
Library Project Marcelo SalvadorLibrary Project Marcelo Salvador
Library Project Marcelo SalvadorDomingos Salvador
 
Firebase for Apple Developers
Firebase for Apple DevelopersFirebase for Apple Developers
Firebase for Apple DevelopersPeter Friese
 
Code to copy Person.java .pdf
Code to copy Person.java .pdfCode to copy Person.java .pdf
Code to copy Person.java .pdfanokhijew
 
F# in the enterprise
F# in the enterpriseF# in the enterprise
F# in the enterprise7sharp9
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmersAlexander Varwijk
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfsooryasalini
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...Corley S.r.l.
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...Walter Dal Mut
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 

Similar to First java-server-faces-tutorial-en (20)

Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Link.javaLink.javapackage com.bookstore.domain.model;import .docx
Link.javaLink.javapackage com.bookstore.domain.model;import .docxLink.javaLink.javapackage com.bookstore.domain.model;import .docx
Link.javaLink.javapackage com.bookstore.domain.model;import .docx
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
Framework Project Portfolio
Framework Project PortfolioFramework Project Portfolio
Framework Project Portfolio
 
Library Project Marcelo Salvador
Library Project Marcelo SalvadorLibrary Project Marcelo Salvador
Library Project Marcelo Salvador
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Firebase for Apple Developers
Firebase for Apple DevelopersFirebase for Apple Developers
Firebase for Apple Developers
 
5-Hibernate.ppt
5-Hibernate.ppt5-Hibernate.ppt
5-Hibernate.ppt
 
Code to copy Person.java .pdf
Code to copy Person.java .pdfCode to copy Person.java .pdf
Code to copy Person.java .pdf
 
F# in the enterprise
F# in the enterpriseF# in the enterprise
F# in the enterprise
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdf
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 

More from techbed

1456.base boot
1456.base boot1456.base boot
1456.base boottechbed
 
1455.ata atapi standards - 1-7
1455.ata atapi standards - 1-71455.ata atapi standards - 1-7
1455.ata atapi standards - 1-7techbed
 
1454.ata features
1454.ata features1454.ata features
1454.ata featurestechbed
 
1432.encoding concepts
1432.encoding concepts1432.encoding concepts
1432.encoding conceptstechbed
 
Flash cs4 tutorials_2009
Flash cs4 tutorials_2009Flash cs4 tutorials_2009
Flash cs4 tutorials_2009techbed
 
Photoshop tut
Photoshop tutPhotoshop tut
Photoshop tuttechbed
 
Part 6 debugging and testing java applications
Part 6 debugging and testing java applicationsPart 6 debugging and testing java applications
Part 6 debugging and testing java applicationstechbed
 
Lab 7b) test a web application
Lab 7b) test a web applicationLab 7b) test a web application
Lab 7b) test a web applicationtechbed
 
Lab 7a) debug a web application
Lab 7a) debug a web applicationLab 7a) debug a web application
Lab 7a) debug a web applicationtechbed
 
What is struts_en
What is struts_enWhat is struts_en
What is struts_entechbed
 
Part 7 packaging and deployment
Part 7 packaging and deploymentPart 7 packaging and deployment
Part 7 packaging and deploymenttechbed
 
Lab 6) package and deploy a j2 ee application
Lab 6) package and deploy a j2 ee applicationLab 6) package and deploy a j2 ee application
Lab 6) package and deploy a j2 ee applicationtechbed
 
Lab 5b) create a java server faces application
Lab 5b) create a java server faces applicationLab 5b) create a java server faces application
Lab 5b) create a java server faces applicationtechbed
 
Lab 5a) create a struts application
Lab 5a) create a struts applicationLab 5a) create a struts application
Lab 5a) create a struts applicationtechbed
 
Part 5 running java applications
Part 5 running java applicationsPart 5 running java applications
Part 5 running java applicationstechbed
 
Part 4 working with databases
Part 4 working with databasesPart 4 working with databases
Part 4 working with databasestechbed
 
Part 3 web development
Part 3 web developmentPart 3 web development
Part 3 web developmenttechbed
 
Lab 4) working with databases
Lab 4) working with databasesLab 4) working with databases
Lab 4) working with databasestechbed
 
Lab 3) create a web application
Lab 3) create a web applicationLab 3) create a web application
Lab 3) create a web applicationtechbed
 
Part 2 java development
Part 2 java developmentPart 2 java development
Part 2 java developmenttechbed
 

More from techbed (20)

1456.base boot
1456.base boot1456.base boot
1456.base boot
 
1455.ata atapi standards - 1-7
1455.ata atapi standards - 1-71455.ata atapi standards - 1-7
1455.ata atapi standards - 1-7
 
1454.ata features
1454.ata features1454.ata features
1454.ata features
 
1432.encoding concepts
1432.encoding concepts1432.encoding concepts
1432.encoding concepts
 
Flash cs4 tutorials_2009
Flash cs4 tutorials_2009Flash cs4 tutorials_2009
Flash cs4 tutorials_2009
 
Photoshop tut
Photoshop tutPhotoshop tut
Photoshop tut
 
Part 6 debugging and testing java applications
Part 6 debugging and testing java applicationsPart 6 debugging and testing java applications
Part 6 debugging and testing java applications
 
Lab 7b) test a web application
Lab 7b) test a web applicationLab 7b) test a web application
Lab 7b) test a web application
 
Lab 7a) debug a web application
Lab 7a) debug a web applicationLab 7a) debug a web application
Lab 7a) debug a web application
 
What is struts_en
What is struts_enWhat is struts_en
What is struts_en
 
Part 7 packaging and deployment
Part 7 packaging and deploymentPart 7 packaging and deployment
Part 7 packaging and deployment
 
Lab 6) package and deploy a j2 ee application
Lab 6) package and deploy a j2 ee applicationLab 6) package and deploy a j2 ee application
Lab 6) package and deploy a j2 ee application
 
Lab 5b) create a java server faces application
Lab 5b) create a java server faces applicationLab 5b) create a java server faces application
Lab 5b) create a java server faces application
 
Lab 5a) create a struts application
Lab 5a) create a struts applicationLab 5a) create a struts application
Lab 5a) create a struts application
 
Part 5 running java applications
Part 5 running java applicationsPart 5 running java applications
Part 5 running java applications
 
Part 4 working with databases
Part 4 working with databasesPart 4 working with databases
Part 4 working with databases
 
Part 3 web development
Part 3 web developmentPart 3 web development
Part 3 web development
 
Lab 4) working with databases
Lab 4) working with databasesLab 4) working with databases
Lab 4) working with databases
 
Lab 3) create a web application
Lab 3) create a web applicationLab 3) create a web application
Lab 3) create a web application
 
Part 2 java development
Part 2 java developmentPart 2 java development
Part 2 java development
 

Recently uploaded

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 

Recently uploaded (20)

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 

First java-server-faces-tutorial-en

  • 1. First step with JavaServer Faces using Eclipse This tutorial facilitates the first steps with the quite new framework JavaServer Faces (JSF). Step by step an example application (a library) will be created, which illustrate the different elements of the framework. The example application will provide the following functionality. • Display a book overview (list of books) • Add, edit and delete a book Generals Author: Sascha Wolski http://www.laliluna.de/tutorials.html Tutorials for Struts, EJB, xdoclet, JSF, JSP and eclipse. Date: December, 21 2004 Source code: The sources do not contain any project files of eclipse or libraries. Create a new project following the tutorial, add the libraries as explained in the tutorial and then you can copy the sources in your new project. http://www.laliluna.de/assets/tutorials/first-java-server-faces-tutorial.zip PDF Version des Tutorials: http://www.laliluna.de/assets/tutorials/first-java-server-faces-tutorial-en.pdf Development Tools Eclipse 3.x MyEclipse plugin 3.8 (A cheap and quite powerful Extension to Eclipse to develop Web Applications and EJB (J2EE) Applications. I think that there is a test version availalable at MyEclipse.) Application Server Jboss 3.2.5 You may use Tomcat here if you like. Create a JavaServer faces project Create a new web project. File > New > Project.
  • 2. Set a nice name and add the JSTL Libraries to the project.
  • 3. Add the JavaServer faces Capabilities. Right click on the project and choose MyEclipse > Add JSF Capabilities.
  • 4.
  • 5. The class Book Add an new package de.laliluna.tutorial.library und create a new class named Book. Open the class and add the following private properties: • id • author • title • available Generate a getter- and setter-method for each property. Right click on the editor window and
  • 6. choose Source > Generate Getter- and Setter Methods. Furthermore you have to add a constructor, which set the properties if you initialisize the instance variable of the newly object. The following source code show the class book. public class Book implements Serializable { // ------------------ Properties -------------------------------- private long id; private String author; private String title; private boolean available; // ------------------ Constructors -------------------------------- public Book(){} public Book(long id, String author, String title, boolean available){ this.id = id; this.author = author; this.title = title; this.available = available; } // ------------------ Getter and setter methods --------------------- public String getAuthor() { return author; } public void setAuthor(String author) {
  • 7. this.author = author; } public boolean isAvailable() { return available; } public void setAvailable(boolean available) { this.available = available; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } Add a getter and setter for the class. /** * Set the properties * @param book */ public void setBook(Book book){ this.setId(book.getId()); this.setAuthor(book.getAuthor()); this.setTitle(book.getTitle()); this.setAvailable(book.isAvailable()); } /** * @return book object */ public Book getBook(){ return new Book(this.getId(), this.getAuthor(), this.getTitle(), this.isAvailable()); } The database class We use a class to provide some test data without using a database. Download the sample application of this tutorial and copy the class SimulateDB.java find in the folder src/de/laliluna/tutorial/library/ in the package de.laliluna.tutorial.library. The class BookList Create a futher class BookList in the package de.laliluna.library. This class inlcudes the property books, which represent the list of books. Generate a getter- and seter-method for the property books and change the getter-method like the following. public class BookList { // ------------------------- Properties --------------------------- Collection books; // ------------------------- Getter and Setter --------------------
  • 8. /** * @return collection of books */ public Collection getBooks(){ SimulateDB simulateDB = new SimulateDB(); /* Holt sich die Session auf dem Externen Context */ Map session = FacesContext.getCurrentInstance().getExternalContext ().getSessionMap(); /* Lies alle Bücher auf der simulierten Datenbank aus */ books = simulateDB.getAllBooks(session); return books; } /** * @param books The books to set. */ public void setBooks(Collection books) { this.books = books; } } Your package explorer will look like the picture below. Action listener methods To provide that a user can add, edit or delete a book, we have to include the appropriate functionality. This functionality will be implemented in action listener methods / classes. If an event occur (ex.: a user clicks on a link) an action listener method / class will be called and processed. Open the class Book and add four methods , which process the following functionality. • Initializise a book • Edit a book • Save a book • Delete a book
  • 9. Initialize a book /** * Initial the properties of the class with null * @param event */ public void initBook(ActionEvent event){ /* * init the book object */ this.setBook(new Book()); } Edit a book /** * Get the book to edit and assign it to the bean * * @param event */ public void selectBook(ActionEvent event){ SimulateDB simulateDB = new SimulateDB(); /* * Get the session map of the external context */ Map session = FacesContext.getCurrentInstance().getExternalContext(). getSessionMap(); /* * Find the UIParameter component by expression */ UIParameter component = (UIParameter) event.getComponent().findComponent ("editId"); /* * parse the value of the UIParameter component */ long id = Long.parseLong(component.getValue().toString()); /* * get the book by id and set it in the local property */ this.setBook(simulateDB.loadBookById(id, session)); } Save a book /** * Add or update the book in the simulated database. * If the book id is not set the book will be added * otherwise the book will be updated * * @param event */ public void saveBook(ActionEvent event){ SimulateDB simulateDB = new SimulateDB(); /* * Get the session map of the external context */ Map session = FacesContext.getCurrentInstance().getExternalContext(). getSessionMap();
  • 10. /* * Add or update the book in the simulated database */ simulateDB.saveToDB(this.getBook(), session); } Delete a book /** * Delete a book in the simulated database * * @param event */ public void deleteBook(ActionEvent event){ SimulateDB simulateDB = new SimulateDB(); /* * Get the session map of the external context */ Map session = FacesContext.getCurrentInstance().getExternalContext(). getSessionMap(); /* * Find the UIParameter component by expression */ UIParameter component = (UIParameter) event.getComponent().findComponent ("deleteId"); /* * parse the value of the UIParameter component */ long id = Long.parseLong(component.getValue().toString()); /* * delete the book by id */ simulateDB.deleteBookById(id, session); }
  • 11. The file faces-config.xml The faces-config.xml is the central configuration file of JavaServer faces. In this file you define the workflow of the application (on which action which site will be processed) , the managed bean classes by JSF and something more. The workflow of the library application looks like the following. We define a navigation rule for this workflow. Open the file faces-config.xml and add the following configuration. <faces-config> <!-- Navigation rules --> <navigation-rule> <description>List of books</description> <from-view-id>/listBooks.jsp</from-view-id> <navigation-case> <from-outcome>editBook</from-outcome> <to-view-id>/editBook.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <description>Add or edit a book</description> <from-view-id>/editBook.jsp</from-view-id> <navigation-case> <from-outcome>listBooks</from-outcome> <to-view-id>/listBooks.jsp</to-view-id> <redirect/> </navigation-case> </navigation-rule> </faces-config> <navigation-rule> Define a navigation rule <from-view-id>/listBooks.jsp</from-view-id> Define the jsp file for which the containing navigation rule is relevant. <navigation-case> Define a navigation case <from-outcome>editBook</from-outcome> Define a name for this navigation case <to-view-id>/listBooks.jsp</to-view-id> Refers to the setted JSP File <redirect/> All parameters saved in the request will be losed when you set this tag.
  • 12. If you want to access the bean classes in your JSP files, you have to register the bean classes in faces-config.xml Add the following source code. <!-- Managed beans --> <managed-bean> <description> Book bean </description> <managed-bean-name>bookBean</managed-bean-name> <managed-bean-class>de.laliluna.tutorial.library.Book</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <managed-bean> <description> BookList Bean </description> <managed-bean-name>bookListBean</managed-bean-name> <managed-bean-class>de.laliluna.tutorial.library.BookList</managed-bean- class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <managed-bean> Define a managed bean <managed-bean-name>bookBean</managed-bean-name> Define a name for the managed bean. This name is used in the JSP file. <managed-bean-class>de.laliluna.tutorial.library.Book</managed-bean-class> Define the class which represent the bean. <managed-bean-scope>request</managed-bean-scope> Define in which scope the bean is saved. Create the JSP files In the first step we create a JSP file named index.jsp, which forwards the user to the list of books. index.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <jsp:forward page="/listBooks.faces" /> </body> </html> In the second step we create the book overview. listBooks.jsp <%@ page language="java" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>
  • 13. <head> <base href="<%=basePath%>"> <title>List of books</title> </head> <body> <f:view> <h:form id="bookList"> <h:dataTable id="books" value="#{bookListBean.books}" var="book" border="1"> <h:column> <f:facet name="header"> <h:outputText value="Author"/> </f:facet> <h:outputText value="#{book.author}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Title"/> </f:facet> <h:outputText value="#{book.title}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Available"/> </f:facet> <h:selectBooleanCheckbox disabled="true" value="#{book.available}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Edit"/> </f:facet> <h:commandLink id="Edit" action="editBook" actionListener="#{bookBean.selectBook}"> <h:outputText value="Edit" /> <f:param id="editId" name="id" value="#{book.id}" /> </h:commandLink> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Delete"/> </f:facet> <h:commandLink id="Delete" action="listBooks" actionListener="#{bookBean.deleteBook}"> <h:outputText value="Delete" /> <f:param id="deleteId" name="id" value="#{book.id}" /> </h:commandLink> </h:column> </h:dataTable> <h:commandLink id="Add" action="editBook" actionListener="#{bookBean.initBook}"> <h:outputText value="Add a book" /> </h:commandLink> </h:form> </f:view> </body> </html>
  • 14. <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> With directive taglib we include the JSF tag libraries <f:view> Renders a view component. All others tags must be included within this tag. <h:form id="bookList"> Renders a HTML form. <h:dataTable id="books" value="#{bookListBean.books}" var="book" border="1"> Renders a HTML table. The tag is used to loop over a list of data like a for loop. The parameter value assign a list of data, in our case the list of books of the library. With the parameter var you define the variable used to access a element (a book) of the list within the tag (loop). <h:column> <f:facet name="header"> <h:outputText value="Author"/> </f:facet> <h:outputText value="#{book.author}" /> </h:column> Renders a column with a column header. <f:facet name="header"> display the header. <h:outputText value="Author"/> print out a header label. <h:outputText value="#{book.author}" /> refers to the property author of the current element of the list. <h:commandLink id="Edit" action="editBook" actionListener="#{bookBean.selectBook}"> Renders a HTML link, which submits the form. The parameter action define the navigation case, which is processed, after the form submits In our case the navigation case editBook, we have added befor in the faces-config.xml, will be processed. We assign the action listener method to the link with the parameter actionListener. After the user submit the form the method will be processed. The last JSP file includes a form to add and edit a book. editBook.jsp <%@ page language="java" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>Add / Edit a book</title> </head> <body> <f:view> <h:form> <h:inputHidden id="id" value="#{bookBean.id}"/>
  • 15. <h:panelGrid columns="2" border="1"> <h:outputText value="Author:" /> <h:inputText id="author" value="#{bookBean.author}"> </h:inputText> <h:outputText value="Title:" /> <h:inputText id="title" value="#{bookBean.title}"> </h:inputText> <h:outputText value="Available:" /> <h:selectBooleanCheckbox id="available" value="#{bookBean.available}" /> </h:panelGrid> <h:commandButton value="Save" action="listBooks" actionListener="#{bookBean.saveBook}" /> </h:form> </f:view> </body> </html> <h:inputHidden id="id" value="#{bookBean.id}"/> Renders a HTML hidden element. Value refers to the managed bean bookBean and its property id, which indicated in the faces-config.xml. <h:panelGrid columns="2" border="1"> Renders a HTML table with two columns. <h:inputText id="author" value="#{bookBean.author}"> Renders a HTML text field. Value refers to the property author of our class Book. <h:commandButton value="Save" action="listBooks" actionListener="#{bookBean.saveBook}" /> Renders a HTML submit button with the value save and the action listBooks. The action listener method saveBook will be processed if the user submit the form. Test the application Start the jboss and deploy the project as Packaged Archive. Call the project now http://localhost:8080/LibraryWeb/