JSF Bootstrap Example
Hello, in the previous example we learned how to create a sample JSF-HelloWorld application. In this tutorial we will use bootstrap – a responsive CSS framework to convert a boring JSF page into an attractive looking form and a table displaying the form output. We will use the simple structure and will demonstrate the following:
- Student form
- Sending and retrieving data to and from a managed bean and using the same in output page
Table Of Contents
1. Introduction
Bootstrap is a design framework which comes with many classes and not only it helps to create a responsive website but also provides several classes that help to create a good looking website. There are several utility classes which reduce a lot of designing effort.
We will have following components in our login application:
- Student bean – Managed Bean
- input.xhtml – Contains the student form with JSF and bootstrap components
- output.xhtml – Contains a tabular structure to display the form result
- web.xml – Web application configuration file
But before we create the bootstrap enabled JSF application, let’s take a look at the bootstrap framework.
1.1 Bootstrap Components
Bootstrap is an out of the box, ready to use CSS framework with very little customization required. The framework makes core decisions for you by bundling helpful premade CSS components i.e. forms, buttons, menus, etc. The following are the list of components you get as part of this framework:
- CSS – It comes with plenty of CSS files
- Scaffolding – Bootstrap provides a basic structure with grid system, link styles, and background
- Layout Components – List of layout components
- JavaScript Plugins – It contains many jQuery and other JavaScript plug-ins which can be included one by one or all
- Customize – You can customize your components to get your own version of framework
1.2 Bootstrap Benefits
Since it’s an out of box framework it has some advantages i.e.
- Flat trendy design
- Makes design simpler as developer no longer have to fill their time with complex layouts
- Improves performance when browser has to draw all elements to the screen
- Grid system
- It allows the developer to target different screen densities using a 4 level grid system
1.3 Download and Install Bootstrap
Download Bootstrap from here and unzip it into your project’s web folder (i.e. WebContent
) under a subdirectory called resources
so that resources are available to the application and it looks like this:
Now, open up the eclipse IDE and let’s start building the application
2. JSF Bootstrap Example
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 (1.8.0_131), Tomcat7 application server. Having said that, we have tested the code against JDK 1.7 and it works well
2.2 Project Structure
First, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
You may skip project creation and jump directly to the beginning of the example below.
2.3 Project Creation
The below example shows how to use a bootstrap enabled simple registration or login application in JSF. With bootstrap classes, the magic happens where the boring looking registration form turns into a beautiful layout with all the CSS classes already applied.
This section will demonstrate on how to create a Dynamic Web Java project with Eclipse. In eclipse IDE, go to File -> New -> Dynamic web project
In the New Dynamic Project window fill in the below details and click next
- Enter the project name and project location
- Select Target runtime as Apache Tomcat v7.0 from dropdown
- Select Configuration as JavaServer Faces v.2.2 Project from dropdown (this is required to download the java server faces capabilities in your project)
Leave everything as default in this window as we will be making the required java file at a later stage. Simply click next and we will land up on the web-module window
In the Web Module window, leave the context_root
and content_directory
values as default (however, you can change the context_root
but for this application let’s keep it as a default value). Simply, check Generate web.xml deployment descriptor checkbox and click next
In the JSF Capabilities windows, we will require downloading the dependencies (not available by default) so that our project is configured as a JSF module in Eclipse. Add the JSF capabilities to the web project by clicking on the download icon (encircled in fig. 5) and download the JSF 2.2 mojarra implementation
A new pop-up window will open where it will auto lists down the JSF library. Select the JSF 2.2 library and click next (the library name and download destination will be auto populated)
Check the license checkbox and click finish. Eclipse will download the JSF 2.2 library and will display them on the JSF capabilities windows (i.e. fig. 5)
Now the JSF implementation libraries will be listed down on the capabilities page. Select the checkbox (JSF2.2 (Mojarra 2.2.0)) and leave everything else as default. Click Finish
Eclipse will create the project named JSFBootstrap in the workspace and web.xml
will be configured for accepting the JSF requests. It will have the following code:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>JSFBootstrap</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <context-param> <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <context-param> <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> <param-value>resources.application</param-value> </context-param> <listener> <listener-class>com.sun.faces.config.ConfigureListener</listener-class> </listener> </web-app>
Now let’s start building the application!
3. Application Building
3.1 Source File Creation
For the demo, we will have an input file containing the student form and an output file displaying the form result. Right click on project WebContent -> New -> File
Note – In JSF 2.0, it’s recommended to create a JSF page in xhtml format, a file format with .xhtml extension
A pop-up window will open, verify the parent folder location as JSFBootstrap/WebContent
and enter the file name (input.xhtml) and click Finish
Repeat the step where we need to create the file for our application (i.e. fig. 9). Again, verify the parent folder location as JSFBootstrap/WebContent
and enter the filename (output.xhtml) and click Finish
3.1.1 Implementation of Input & Output file
Now in order to use the rich UI components, we need to declare the below namespaces at top of the page in the prepared files
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html">
input.xhtml
Currently, in input.xhtml
we will only have the form based UI components and will add the bootstrap components at a later stage. The action attribute on the button will show the result based on the navigation logic written in createStudentForm()
. Add the following code to it:
<!DOCTYPE HTML> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>JSF Bootstrap Example</title> </h:head> <h:body> <h:form id="studentForm"> <div> <h:outputLabel value="First Name"/> <div> <h:inputText value="#{studentBean.firstName}"/> </div> </div> <div> <h:outputLabel value="Last Name"/> <div> <h:inputText value="#{studentBean.lastName}"/> </div> </div> <div> <h:outputLabel value="Standard"/> <div> <h:inputText value="#{studentBean.standard}"/> </div> </div> <div> <div> <h:commandButton value="Create" action="#{studentBean.createStudentForm}"/> </div> </div> </h:form> </h:body> </html>
output.xhtml
In the output page, JSF will display the #{studentBean.firstName}
, #{studentBean.lastName}
, #{studentBean.standard}
properties value which we will enter in the input page (i.e. input.xhtml
). Add the following code to it:
<!DOCTYPE HTML> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>JSF Bootstrap Example</title> </h:head> <h:body> <table> <thead> <tr> <th>Name</th> <th>Standard</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td><h:outputText value="#{studentBean.firstName}" /><h:outputText value="#{studentBean.lastName}" /></td> <td><h:outputText value="#{studentBean.standard}" /></td> <td><a href="#"></td> <td><a href="#"></td> </tr> </tbody> </table> </h:body> </html>
3.2 Bootstrap Implementation
Bootstrap provide several classes but to make sure it all work, we need to put the code inside the main container div marked with a class container. After that, you can place various responsive utilities inside it.
So we create a div and mark it with the class container. Further, we will create another div with class navbar and sub-div with class navbar-brand which acts as the container for the logo or title of your website.
Next, we create a div with a class row in it and another sub-div with class col-xs-12. This is a part of the structure of the bootstrap responsive hierarchy.
3.2.1 Bootstrap Set-Up
In order to use these files, we need to make a little change to the bootstrap.min.css
so that the fonts are available to CSS file. This is a little hack which we shall use in case we want to use the glyphicons or the icons on the page
In the bootstrap.min.css
file we have to change the reference to the font files from relative path to absolute path of our application, for example, we changed:
url(../fonts/
to url(/JSFBootstrap/resources/fonts/
This will make sure the font files are available no matter how the CSS in included in the web page. We are using the h:outputStylesheet
tag of JSF to include the style sheet as you can see in the code below. This is good way to include the stylesheet or script (h:outputScript
) in the JSF page
3.2.2 Implementation of Bootstrap in Input & Output file
In input page, you will find the structure of the form classes which is going to transform our form into a good looking bootstrap form. We will use the form-horizontal class to create a responsive form and inside we will use the form-group, control-label and form-control classes. To give buttons a good look we are using btn and btn-default class
input.xhtml
<!DOCTYPE HTML> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1" http-equiv="X-UA-Conpatible" /> <h:outputStylesheet library="css" name="bootstrap.min.css" /> <title>JSF Bootstrap Example</title> <style type="text/css"> .col-xs-updated { width: 92% !important; } </style> </h:head> <h:body> <div class="container"> <div class="navbar navbar-inverse"> <div class="navbar-brand">JSF Bootstrap</div> </div> <div class="row"> <div class="col-xs-12 col-xs-updated"> <h:form id="studentForm" styleClass="form-horizontal"> <div class="form-group"> <h:outputLabel value="First Name" styleClass="control-label col-sm-2" /> <div class="col-sm-10"> <h:inputText value="#{studentBean.firstName}" styleClass="form-control" /> </div> </div> <div class="form-group"> <h:outputLabel value="Last Name" styleClass="control-label col-sm-2" /> <div class="col-sm-10"> <h:inputText value="#{studentBean.lastName}" styleClass="form-control" /> </div> </div> <div class="form-group"> <h:outputLabel value="Standard" styleClass="control-label col-sm-2" /> <div class="col-sm-10"> <h:inputText value="#{studentBean.standard}" styleClass="form-control" /> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <h:commandButton value="Create" action="#{studentBean.createStudentForm}" styleClass="btn btn-default" /> </div> </div> </h:form> </div> </div> </div> </h:body> </html>
For tables, we will use the table, table-bordered and table-striped class. Further, we are using glyphicons which are shipped with the bootstrap distribution
output.xhtml
<!DOCTYPE HTML> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1" http-equiv="X-UA-Conpatible" /> <link rel="stylesheet" href="https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/3.3.7/css/bootstrap.min.css" /> <title>JSF Bootstrap Example</title> <style type="text/css"> .tableOutput { margin: 12px; width: 98% !important; } .tab { display: inline-block; margin-left: -2px; } </style> </h:head> <h:body> <div class="container"> <div class="navbar navbar-inverse"> <div class="navbar-brand">JSF Bootstrap</div> </div> <table class="table table-bordered table-striped tableOutput"> <thead> <tr> <th>Name</th> <th>Standard</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td><h:outputText value="#{studentBean.firstName}" /> <span class="tab"><h:outputText value="#{studentBean.lastName}" /></span></td> <td><h:outputText value="#{studentBean.standard}" /></td> <td><a href="#"><span class="glyphicon glyphicon-edit" /></a></td> <td><a href="#"><span class="glyphicon glyphicon-trash" /></a></td> </tr> </tbody> </table> </div> </h:body> </html>
3.3 Java Class Creation
Let’s create the required java files. Right click on src folder New -> Package
A new pop window will open where we will enter the package name, namely com.jsf.bootstrap
Once the package is created in the application, we will need to create the required managed bean class. Right click on the new create package New -> Class
A new pop window will open and enter the file name as StudentBean
. The bean class will be created inside the package –
com.jsf.bootstrap
3.3.1 Implementation of Managed Bean
StudentBean.java
This class has a method createStudentForm()
which interacts with create action event and display the result on the output page in a tabular form
package com.jsf.bootstrap; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean @SessionScoped public class StudentBean { private String firstName; private String lastName; private String standard; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getStandard() { return standard; } public void setStandard(String standard) { this.standard = standard; } public String createStudentForm() { System.out.println("Reading Student Details - Name: " + firstName + " " + lastName + ", Standard: " + standard); return "output"; } }
4. Project Deploy
Once we are ready with all the changes done, let us compile and deploy the application on tomcat7 server. In order to deploy the application on tomcat7, right-click on the project and navigate to Run as -> Run on Server
Tomcat will deploy the application in its webapps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser
Open your favorite browser and hit the following URL. The output page will be displayed
http://localhost:8085/JSF_Bootstrap/faces/input.xhtml
Server name (localhost) and port (8085) may vary as per your tomcat configuration
5. Project Demo
When we will hit the application URL, you will see the form page
Enter the First Name, Last Name, and Standard values and press the Create button
The output page will be displayed showing the entered student details in a tabular format
6. Conclusion
Through this example, we have learned about the integration of bootstrap components in jsf and deploy it using the tomcat7 application server
7. Download the Eclipse Project
This was a JSF Bootstrap example with Eclipse and Tomcat
You can download the full source code of this example here: JSF Bootstrap
I copied your project, imported it, it presents error in the file StudenBean.java (import javax.faces.bean.ManagedBean; -> The import javax.faces cannot be resolved) and (import javax.faces.bean.SessionScoped; -> The import javax.faces cannot be resolved) and (@ManagedBean @SessionScoped -> Multiple markers at this line
– ManagedBean cannot be resolved
to a type
– SessionScoped cannot be resolved
to a type)
why my output is different? error 404
Why Boostrap framwork doesn’t work ?