Headline

Web programming with Technology:JSF

Motivation

This contribution covers the popular approach for web programming with Technology:JSF. Technology:JSF has a great support for the development of user interfaces in the MVC context. This implementation is considered as a typical Language:Java based implementation with an amount of related and commonly used technologies like the Technology:Hibernate persistence API and the Technology:GlassFish application server.

Illustration

The main architecture is based on the MVC pattern. Technology:JSF itself is focussed on the view and the controller. The user interface (view) is provided by facelets, which is based on the Language:XHTML dialect. A facelet contains the necessary GUI components for the specific view and connects them to the corresponding methods of the backend Java Beans (model). The data provided by the Java Beans is stored within a Technology:MySQL database, accessible through Technology:Hibernate with the help of DAOs (data access objects). The following sections provide a specific description of the involved parts.

GUI development

Facelets provide Language:HTML page generation. Since the XML tags for the JSF components can not be displayed by the browser, they have to be changed to corresponding HTML tags via component aliasing. The following example shows the JSF components needed for total and cut of a company:

<h:outputLabel for="total" value="Total:"/>
<h:outputText id="total" value="#{companyBean.total}"/>
<h:commandButton value="cut" actionListener="#{companyBean.cut()}"/>

The three elements model the GUI components for the label "Total", the textfield for the Feature:Total and the button for the Feature:Cut. For example, the

<h:commandButton .../>
is transformed into the HTML tag
<input .../>
. The communication between client and server is provided by Technology:XMLHttpRequest. The needed Language:JavaScript files are automatically generated by the framework.

There is no need to implement the controller since it is provided by the Technology:Servlet API used within the JSF framework.

Managed Beans

The previously introduced command button "cut" invokes the corresponding method

cut
in the Java Bean
CompanyBean
. In context of JSF, such beans are called Managed Beans:

@ManagedBean(name = "companyBean")
@RequestScoped
public class CompanyBean {

	...

	// This is the set of employees for the whole company (loaded previously by the method "loadCompany(int id))".
	private Set<Employee> employees;
	
	...

	// The method returns the current value for total of the loaded company.
	public double getTotal() {
		return total;
	}

	// The method cuts all employees of the loaded company.
	public void cut() {
		// Here we retrieve the session and begin the transaction with Hibernate.
		HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
		DAOFactory daoFactory = DAOFactory.instance(DAOFactory.HIBERNATE);
		// The employeeDAO manages the database interaction.
		EmployeeDAO employeeDAO = daoFactory.getEmployeeDAO();

		// This loop iterates over the previously loaded employees and persists the new salary values.
		for (Employee employee : employees) {
			employee.setSalary(employee.getSalary() / 2);
			employeeDAO.makePersistent(employee);
		}
    
		total = total / 2;

		// Finally, we commit and close the transaction.
		HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
	}

	...

}

The class

CompanyBean
encapsulates the server-side business methods for the application. Responses for GET requests are provided by simple Java getters (e. g.
getTotal()
). POST requests are handled by corresponding methods (e. g.
cut()
) or by Java setters.

The two annotations for the class provide the following features:

@ManagedBean
annotates, that the bean is a managed bean in the context of JSF. The attribute
name
provides the connection point useable within the facelets.

@RequestScope
annotates, that every new request affecting the
CompanyBean
will create a new instance.

The application server Technology:GlassFish provides the necessary container for the beans and manages the application.

Persistence

The principle of the DAO pattern is the exchangeability of the persistence layer. This is provided by a

DAOFactory
, which instantiates the specific DAOs for the used persistence technology. In our case, the technology is Technology:Hibernate. According to the interface GenericDAO.java, every implemented DAO provides the methods to load an entity either by id or by example, to load all entities corresponding to a specific class, or to persist a given entity.

T findById(ID id, boolean lock);
List<T> findAll();
List<T> findByExample(T exampleInstance);
T makePersistent(T entity);
void makeTransient(T entity);

The

T
stands for either the class
Company
, or the class
Department
, or the class
Employee
. The concrete methods for Hibernate are implemented in GenericDAOHibernate.java. This structure enables the Java Beans to perform data-affecting actions mostly independent from the persistence implementation:

@ManagedBean(name = "companyBean")
@RequestScoped
public class CompanyBean {
        
	...

	public void cut() {
		// There has to be a transaction before creating hibernate requests.
		HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();

		// Retrieve the Hibernate DAOFactory for creating the employee DAO.
		DAOFactory daoFactory = DAOFactory.instance(DAOFactory.HIBERNATE);
		EmployeeDAO employeeDAO = daoFactory.getEmployeeDAO();
        
		// Cut all employees and save them.
		for (Employee employee : employees) {
			employee.setSalary(employee.getSalary() / 2);
			employeeDAO.makePersistent(employee);
		}
        
		// Calculate new total value.
		total = total / 2;

		// The transaction commits the data and ends.
		HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
	}

	...

}

There is an issue to be solved in the future: The transaction should be invoked by annotations or any automated transaction management instead of using corresponding methods with the help of

HibernateUtil
. If there is no Hibernate persistence, the calls will lead to exceptions.

Architecture

The facelets (company.xhtml, department.xhtml, employee.xhtml) are located in the folder jsf/web/. There is a template.xhtml as well, which arranges the main UI components of each view. The folder jsf/web/resources/css/ contains the corresponding Language:CSS files.

The navigation between the different facelets is managed with the help of the file faces-config.xml, while the starting page and the class for the controller servlet is defined in the web.xml.

The jsf/src/java/ folder contains all relevant code for the realization of the main features (except Feature:Browsing):

Usage

You need an sql-server to use this application. In this tutorial both will be handled by XAMPP (http://www.apachefriends.org/en/xampp.html).

You can use the company.sql and sampleCompany.sql of Contribution:html5tree for the jsf project.

  • Download and install XAMPP
  • Open the "XAMPP Control Panel" and start "Apache" and "MySQL"
  • Use the guideline of Contribution:mySqlMany up to "Populate tables..."
After the database is running, follow the next steps:

  • To start the application, you have to download the sources from github
  • Open the project with Technology:NetBeans (http://netbeans.org/)
  • Select the project, right click and run
  • The glassfish-server (and a browser window) with the application will start automatically
The project is implemented with Technology:NetBeans 7.0.1. You will need the full version with an installed Technology:GlassFish Application server.


There are no revisions for this page.

User contributions

    This user never has never made submissions.

    User edits

    Syntax for editing wiki

    For you are available next options:

    will make text bold.

    will make text italic.

    will make text underlined.

    will make text striked.

    will allow you to paste code headline into the page.

    will allow you to link into the page.

    will allow you to paste code with syntax highlight into the page. You will need to define used programming language.

    will allow you to paste image into the page.

    is list with bullets.

    is list with numbers.

    will allow your to insert slideshare presentation into the page. You need to copy link to presentation and insert it as parameter in this tag.

    will allow your to insert youtube video into the page. You need to copy link to youtube page with video and insert it as parameter in this tag.

    will allow your to insert code snippets from @worker.

    Syntax for editing wiki

    For you are available next options:

    will make text bold.

    will make text italic.

    will make text underlined.

    will make text striked.

    will allow you to paste code headline into the page.

    will allow you to link into the page.

    will allow you to paste code with syntax highlight into the page. You will need to define used programming language.

    will allow you to paste image into the page.

    is list with bullets.

    is list with numbers.

    will allow your to insert slideshare presentation into the page. You need to copy link to presentation and insert it as parameter in this tag.

    will allow your to insert youtube video into the page. You need to copy link to youtube page with video and insert it as parameter in this tag.

    will allow your to insert code snippets from @worker.