JavaServerTM Faces (JSF) is a Java-based Web application framework intended to simplify development of user interfaces for Java Web applications. JSF provides artifacts to easily assemble reusable UI components in a page, connect these components to an application data source, and wire client-generated events to server-side event handlers.
Contents |
Downloading JSF 1.2 binaries
You need JSF framework libraries to develop a JSF-based Java Web Application. The binaries can be downloaded from https://javaserverfaces.dev.java.net/files/documents/1866/123652/mojarra-1.2_12-binary.zip.
The JSF framework also requires the Java Standard Tag Library (JSTL), which can be downloaded from the Apache web site at http://jakarta.apache.org/site/downloads/downloads_taglibs-standard.cgi.
Creating a JSF Web project
To create and develop Java Web applications in Aptana Studio, Studio must be installed as a plugin into an Eclipse bundle with WTP. The resulting Java Web projects can be deployed to Java hosted sites via Aptana Cloud Connect.
To install Aptana Studio:
- Download and install Eclipse IDE for Java EE Developers from the Eclipse Download Site.
- Install Aptana Studio as a Plugin for Eclipse 3.4 from the Aptana Studio Update Site.
To add a local Tomcat server for testing:
- Download and install Tomcat Server from http://tomcat.apache.org/download-60.cgi.
- From the Project view, right-click and select New > Other > Server > server.
- Select Apache > Tomcat 6.0 and browse to the Tomcat installation folder.
To create a JSF Web project:
- Right click in the Project view and Select New > Other > Web > Dynamic Web project.
- In the Configuration section of the dialog that appears, click Modify....
- In the Project Facets dialog, change the version of Dynamic Web Module from 2.4 to 2.5.
- Select JavaServer Faces and change the version from 1.1 to 1.2.
- Click OK.
- Back in the Dynamic Web project dialog, select JavaServer Faces v1.2 Project from the drop-down menu in the Configuration section.
- Provide a Project Name and click Next twice.
- On the JSF Capabilities pane, select Server Supplied JSF Implementation and click Finish to create the project.
To add the JSF libraries to WEB-INF/lib:
- In the Project view, expand WebContent > WEB-INF > lib in the JSF project.
- From the OS File Sytem (Finder/Explorer/Nautilus) expand the JSF 1.2 binary folder (mojarra-1.2_12-b01-FCS > lib).
- Drag the jsf-api.jar and jsf-impl.jar libraries to the WEB-INF > lib folder in the Project view.
- Drag the jstl.jar and standard.jar libraries from jakarta-taglibs-standard-1.1.2/lib to the WEB-INF > lib folder in the Project view.
- Right-click on the project node and select New > JSP (or Other > Web > JSP).
- In the dialog that appears, enter index.jsp as the name of the file and click Next.
- On the Select JSP Template pane, select New JavaServer Faces (JSF) Page (html) and click Finish.
- After index.jsp is created, double click WEB-INF > web.xml to edit it.
- Modify the <welcome-file-list> node to include only faces/index.jsp as the welcome file.
<welcome-file-list> <welcome-file>faces/index.jsp</welcome-file> </welcome-file-list>
Running the JSF application locally
Test the project locally by right-clicking on the project and selecting Run As > Run on Server. This should start the Tomcat server and show the default page of the application in an embedded browser in the editor.
Accessing a database from the JSF application
Create the datasource JNDI refenrece in the local Tomcat
In this section we will be accessing a database via a Datasource JNDI predefined in the Cloud site. In order to test this application locally first you must create a database (say sample) in a local Mysql installation and reference it from your local Tomcat installation. Make sure to give the JNDI name as jdbc/mysql
- Edit <local-tomcat-installation>/conf/context.xml and add the following to it
<Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/sample" username="root" password="" maxActive="20" maxIdle="10" maxWait="-1"/>
- Alternatively, if you want to use your cloude site Mysql then change the Resource information accordingly. Replace the {cloud_site_name} with domain name of your cloud site. {cloud_site_username}, {cloud_site_password}, with the username and password you used to login in to the cloud site.
<Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://{cloud_site_name}:3306/{cloud_site_name}_public" username="{cloud_site_username}" password="{cloud_site_password}" />
Creating a Helper class to access database:
Let us first create a Helper class to access the database. This class will be used by JSF backing beans to display the data in a JSF DataTable component.
- Right click on the project node and select New > class.
- Give the Class name as DatabaseHelper.
- Give the package name as com.sample.jsf.
- Add the follwiing code to the class
package com.test; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class DatabaseHelper { private static Connection createConnection() throws NamingException, SQLException { Context ctx = new InitialContext(); if (ctx == null) { throw new NamingException("No initial context"); } Context envContext = (Context) ctx.lookup("java:/comp/env"); if (envContext == null) { throw new NamingException("No environment context"); } DataSource ds = (DataSource) envContext.lookup("jdbc/mysql"); if (ds == null) { throw new NamingException("No data source"); } Connection conn = ds.getConnection(); if (conn == null) { throw new SQLException("No database connection"); } return conn; } public static void populateDatabase() { Connection connection; try { connection = createConnection(); String dropSql = "drop table if exists customer"; executeUpdate(connection, dropSql); String createSql = "create table customer(" + "id integer," + "First varchar(20)," + "Last varchar(20)" + ")"; executeUpdate(connection, createSql); String insertSql = "insert into customer values (101, \"Paul\", \"Colton\")"; executeUpdate(connection, insertSql); insertSql = "insert into customer values ( 102, \"Joelle\", \"Lam\")"; executeUpdate(connection, insertSql); insertSql = "insert into customer values ( 102, \"Sandip\", \"Chitale\")"; executeUpdate(connection, insertSql); insertSql = "insert into customer values ( 102, \"Shalom\", \"Gibly\")"; executeUpdate(connection, insertSql); } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public static List<CustomerBean> getCustomers() { Statement stmt = null; List<CustomerBean> customers = new ArrayList<CustomerBean>(); try { String sql = "select * from customer"; Connection connection = createConnection(); stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setQueryTimeout(30); ResultSet resultSet = stmt.executeQuery(sql); while (resultSet.next()) { int id = resultSet.getInt(1); String first = resultSet.getString(2); String last = resultSet.getString(3); customers.add(new CustomerBean(id, first, last)); } } catch (SQLException exc) { try { if (stmt != null) { stmt.close(); } } catch (SQLException e) { e.printStackTrace(); } } catch (NamingException e) { e.printStackTrace(); } return customers; } private static void executeUpdate(Connection connection, String sql) { Statement stmt = null; try { stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setQueryTimeout(30); stmt.executeUpdate(sql); } catch (SQLException exc) { try { if (stmt != null) { stmt.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
Creating the JSF backing beans
JSF backing beans are the model for the JSF UI in the JSP page. We need two beans:
- CustomertBean corresponds to a Customer record in a database table.
- ResultBean holds the list of customer beans we obtained by quering the database.
To create the backing beans:
- Double-click WebContent/WEB-INF/faces-config.xml (or right-click on faces-config.xml and select Open With > faces Config Editor).
- Select ManagedBean from the bottom tab.
- Click Add. In the dialog that appears, select Create New Java Class and click Next.
- Enter CustomerBean as the Java Class name and com.sample.jsf as the package name and click Next.
- Select session as the managed bean scope.
- Repeat steps 2-4 to add a Managed bean called ResultBean.
- Type the following code inside the class CustomerBean:
private int id; private String first; private String last;
- Selct the above code, right click and select Source > Generate Getters and Setters.
- In the dialog that appears, select id, first, last and click OK to create the getter and setters.
- Add the following constructor to the class:
public CustomerBean(int id, String first, String last) { this.id = id; this.first = first; this.last = last; }
Adding code to Result Bean
Type the following code inside the class ResultBean and create the getter and setter as follows:
import java.util.List;
public class ResultBean {
private List<CustomerBean> list = null;
public ResultBean(){
DatabaseHelper.populateDatabase();
}
public List<CustomerBean> getList() {
// get the customer list lazily.
if (list == null) {
list = DatabaseHelper.getCustomers();
}
return list;
}
public void setList(List<CustomerBean> newlist) {
this.list = newlist;
}
}
Note, the constructor of the class creates and populates a table called customer using the database Helper class. The getter method for the property list fetches the data back from the database and initializes the property list with CustomerBean. We use DatabaseHelper.getCustomers() method for this purpose.
Adding a JSF Data Table component to the JSP
The next step is to add a JSF Data Table to the JSP page and bind it to the ResultBean. The DataTable will fetch the list of Customer Beans from the Result Bean and display it in a tabular form. Open the JSP file in the JSP Editor and add the following code to it. The code must go between the <f:view></f:view> tags.
<body>
<f:view>
<h:dataTable id="table" rows="20"
value="#{resultBean.list}" var="customer">
<h:column>
<f:facet name="header">
<h:outputText value="Id" />
</f:facet>
<h:outputText id="id" value="#{customer.id}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="First Name" />
</f:facet>
<h:outputText id="first" value="#{customer.first}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Last Name" />
</f:facet>
<h:outputText id="last" value="#{customer.last}" />
</h:column>
</h:dataTable>
</f:view>
</body>
ResultBean.getBean() is bound to the value attribute of the Data Table. This is done via the JSP Expression Language (EL) construct value="#{resultBean.list}". The properties of the Customer bean are bound to each column of the Data table via the EL construct (for example, value="#{customer.first}).
Deploy the application and the result should look roughly like the following:
Styling the JSF Data Table
The bare bones result table has no styles. It is possible to associate CSS styles to the table as follows:
- Right click on the WebContent folder and select New > Other > Web > CSS to create a file called stylesheet.css.
- Add the following code to this file:
.table { background-color: #7171A5; border: 5px outset #71A5A5; border-collapse: collapse; font-family: sans-serif; font-size: 14pt; padding: 10px; width: 100%; } .column { text-align: center; width: 15%; } .header { background-color: #A5A5A5; color: #FFFFFF; font-weight: bold; text-align: center; } .row-even { } .row-odd { background-color: #717171; }
Modifying index.jsp to add the styles
- Add a reference to stylesheet.css to the head of index.jsp:
<head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <title>Datasource Test</title> <link rel="stylesheet" type="text/css" href='<%=request.getContextPath() + "/stylesheet.css"%>'> </head>
- Add the style information to the <dataTable> tag:
<h:dataTable columnClasses="column, column, column" headerClass="header" rowClasses="row-even,row-odd" styleClass="table" id="table" rows="20" value="#{ResultBean.list}" var="customer">
Deploy the application and now it should look similar to the following:
Related Documents
Creating and Deploying Java Projects
Accessing MySQL on a Java Hosted Site


