jsf

JSF Datepicker Example

Hello, in this tutorial we will implement the datepicker component in jsf and we will use bootstrap – a responsive CSS framework to demonstrate the following,

  • Registration Form
  • Sending and retrieving data to and from a managed bean and using the same in output page

This example will show how to integrate and implement the datepicker module in a jsf enabled form.
 
 
 

1. Introduction

A datepicker is an interactive dropdown that makes it easy to choose the date from a calendar instead of typing it manually. It’s a great way to avoid user errors because a user can see the corresponding day of the week for each date. Plus, it gives the form a little extra interactive shine!
We will have the following components in our application:

  • Registration Bean – Managed bean class for the registration form
  • input.xhtml – Contains the registration form
  • output.xhtml – Contains a tabular structure to display the registration form result
  • formatDatePicker.js – Contains the datepicker javascript code
  • web.xml – Web application configuration file

But before we create the application let’s take a look at the datepicker utility.

1.1 Datepicker Plugin

Datepickers in jQueryUI allow users to enter dates easily and visually. Developers can customize the date format, restrict the selectable date ranges and add in buttons & other navigation options easily.

jQueryUI provides datepicker() method that creates a datepicker and changes the appearance of HTML elements on a page by adding new CSS classes. Transforms the input, div and span elements in the wrapped set into a datepicker control.

1.2 Datepicker Syntax

The datepicker() method can be used in two forms:

  • $(selector, context).datepicker (options) method
  • $(selector, context).datepicker ("action", [params]) method

The datepicker’s options() method declares that an input element (or div or span) depending on how the developer chooses to display the calendar, should be managed as a datepicker.

The options parameter is an object that specifies the behavior and appearance of the datepicker elements. If the developer wants to use a wide range of options they might use this option.

1.3 Datepicker Pre-requisites

To create and enable the datepicker component in jsf, developers will need the following prerequisites:

  1. jQuery 1.x – This popular JavaScript library is needed by the date picker
  2. Bootstrap 3.x – The datepicker works with bootstrap in order to enhance the user experience and make it more interactive

After adding the prerequisites, the header of the file should look something like this:

sample.xhtml

<!-- DatePicker JavaScript & CSS -->
<script type="text/javascript" src="https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9jb2RlLmpxdWVyeS5jb20vjquery-1.12.4.js" />
<script type="text/javascript" src="https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9jb2RlLmpxdWVyeS5jb20vui/1.12.1/jquery-ui.js" />
<link rel="stylesheet" href="https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9jb2RlLmpxdWVyeS5jb20vui/1.12.1/themes/base/jquery-ui.css" />

Now, open up the Eclipse IDE and let’s start building the application.

1.4 Datepicker Implementation

In order to use the datepicker component, we will have to add the below jQuery code in the script tag so that component can be initialized at the page load,

jQuery Code

$(document).ready(function() {
   $(".datepicker").datepicker({
      dateFormat: 'dd MM, yy',
      changeMonth: true,
      changeYear: true,
      yearRange: "1960:2017"
   });
});

In order to ensure jsf best practices, we will include this code in a javascript file by using the h:outputScript tag in the file. Let’s take a look at the sample code below,

sample.xhtml

<h:outputScript library="js" name="formatDatePicker.js" />

2. JSF Datepicker 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!

Fig. 1: Jsf Datepicker Application Project Structure
Fig. 1: Jsf Datepicker Application Project Structure

2.3 Project Creation

The below example shows how to implement datepicker in a sample form application. With datepicker and bootstrap classes the magic happens where the boring looking 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

Fig. 2: Create Dynamic Web Project
Fig. 2: Create 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)

Fig. 3: Project Details
Fig. 3: Project Details

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

Fig. 4: Java Src Window
Fig. 4: Java Src 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 the first application let’s keep it as a default value). Simply, check Generate web.xml deployment descriptor checkbox and click next

Fig. 5: Web Module Window
Fig. 5: Web Module Window

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

Fig. 6: JSF Capabilities Window
Fig. 6: JSF Capabilities Window

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)

Fig. 7: JSF Capabilities Download Window
Fig. 7: JSF Capabilities Download Window

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. 6)

Fig. 8: JSF Capabilities License Window
Fig. 8: JSF Capabilities License Window

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

Fig. 9: JSF Capabilities Library Selection Window
Fig. 9: JSF Capabilities Library Selection Window

Eclipse will create the project named JSF Datepicker in the workspace and web.xml will be configured for accepting the JSF requests. It will have the following code:

web.xml

<?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>JSF Datepicker</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

Following are the steps involved in developing this application:

3.1 Source File Creation

For the demo, we will have an input file containing the registration 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

Fig. 10: File Creation
Fig. 10: File Creation

A pop-up window will open, verify the parent folder location as JSF Datepicker/WebContent and enter the file name (input.xhtml) and click Finish

Fig. 11: input.xhtml
Fig. 11: input.xhtml

Repeat the step where we need to create the file for our application (i.e. fig. 10). Again, verify the parent folder location as JSF Datepicker/WebContent and enter the filename (output.xhtml) and click Finish

Fig. 12: output.xhtml
Fig. 12: output.xhtml

3.1.1 Implementation of Input & Output file

Here in the input.xhtml, we will have the form based UI components and will add the code to evoke the datepicker module on page load. The action attribute on the button will show the result based on the navigation logic written in createRegistrationForm(). Add the following code to it:

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" />
 
    <!-- DatePicker JavaScript & CSS -->
	<script type="text/javascript" src="https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9jb2RlLmpxdWVyeS5jb20vjquery-1.12.4.js" />
	<script type="text/javascript" src="https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9jb2RlLmpxdWVyeS5jb20vui/1.12.1/jquery-ui.js" />
	<link rel="stylesheet" href="https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9jb2RlLmpxdWVyeS5jb20vui/1.12.1/themes/base/jquery-ui.css" />

	 <h:outputScript library="js" name="formatDatePicker.js" />
	 <h:outputStylesheet library="css" name="bootstrap.min.css" />
	 
    <title>JSF Datepicker Example</title>
    <style type="text/css">
        .col-xs-updated {        
            width: 92% !important;
        }
    </style>
</h:head>
<h:body>
    <div class="container">
        <div class="nav navbar-nav">
            <div class="navbar-brand">JSF Datepicker</div>
        </div>
        <div class="row">
            <div class="col-xs-12 col-xs-updated">
                <h:form id="registrationForm" 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="#{registrationBean.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="#{registrationBean.lastName}" styleClass="form-control" />
                        </div>
                    </div>
                    <div class="form-group">
                        <h:outputLabel value="DOB" styleClass="control-label col-sm-2" />
                        <div class="col-sm-10">
                            <h:inputText value="#{registrationBean.dateOfBirth}" styleClass="form-control datepicker" />
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <h:commandButton value="Create" action="#{registrationBean.createRegistrationForm}" styleClass="btn btn-primary" />
                        </div>
                    </div>
                </h:form>
            </div>
        </div>
    </div>
</h:body>
</html>

In the output page, JSF will display the #{registrationBean.firstName}, #{registrationBean.lastName}, #{registrationBean.dateOfBirth} properties value which you will enter in the input page. Add the following code to it:

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 Datepicker 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="nav navbar-nav">
            <div class="navbar-brand">JSF Datepicker</div>
        </div>
        <table class="table table-bordered table-striped tableOutput">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Date Of Birth</th>
                    <th></th>                
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><h:outputText value="#{registrationBean.firstName}" /> <span class="tab"><h:outputText value="#{registrationBean.lastName}" /></span></td>
                    <td><h:outputText value="#{registrationBean.dateOfBirth}" /></td>
                    <td><a href="#"><span class="glyphicon glyphicon-trash" /></a></td>
                </tr>
            </tbody>
        </table>
    </div>
</h:body>
</html>

3.2 Java Class Creation

Let’s create the required java files. Right click on src folder New -> Package

Fig. 13: Java Package Creation
Fig. 13: Java Package Creation

A new pop window will open where we will enter the package name, namely com.jsf.datepicker

Fig. 14: Java Package Name (com.jsf.datepicker)
Fig. 14: Java Package Name (com.jsf.datepicker)

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

Fig. 15: Java Class Creation
Fig. 15: Java Class Creation

A new pop window will open and enter the file name as RegistrationBean. The bean class will be created inside the package – com.jsf.datepicker

Fig. 16: Java Class (RegistrationBean.java)
Fig. 16: Java Class (RegistrationBean.java)

This class has a method createRegistrationForm() method which interacts with create action event and display the result on the output page in a tabular form. Add the following code to it:

RegistrationBean.java

package com.jsf.datepicker;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean @SessionScoped
public class RegistrationBean {

	private String lastName;
	private String firstName;
	private String dateOfBirth;

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getDateOfBirth() {
		return dateOfBirth;
	}

	public void setDateOfBirth(String dateOfBirth) {
		this.dateOfBirth = dateOfBirth;
	}

	public String createRegistrationForm() {
		System.out.println("Registration Form Details - Name: " + firstName + " " + lastName + ", DOB: " + dateOfBirth);
		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

Fig. 17: How to Deploy Application On Tomcat
Fig. 17: How to Deploy Application On Tomcat

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

Fig. 18: Tomcat Processing
Fig. 18: Tomcat Processing

Open your favorite browser and hit the following URL. The output page will be displayed.

http://localhost:8082/JSFDatepicker/faces/input.xhtml

Server name (localhost) and port (8082) may vary as per your tomcat configuration

5. Project Demo

When we will hit the application url, you will see the registration form page

Fig. 19: Input Page - Registration Form
Fig. 19: Input Page – Registration Form

Enter the First Name, Last Name, and DOB values and press the Create button

Fig. 20: User Details
Fig. 20: User Details

The output page will be displayed showing the entered details in a tabular format

Fig. 21: Output Page
Fig. 21: Output Page

Hope this helped :)

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 Datepicker example with Eclipse and Tomcat.

Download
You can download the full source code of this example here: JSF Datepicker

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Thierry Salmon
5 years ago

Hello

I was happy to find your code for the Date Picker. A feature missing in JSF which is otherwise a good framework.

Thanks

Back to top button