Login and Registration is one of the most required module of any project. This tutorial explains how to implement login and registration functionality in your JSF project. The example application in this tutorial is named “RichLRApplication” which uses RichFaces as JSF implementation and library of rich featured components. We have selected RichFaces for the application because it provides a large number of useful components which are enough to start with. RichFaces components are AJAX enabled which increases the responsiveness of the application.

In this application, Login page appears first in front of the user. User fills the login and password information and enters into the application for further actions. After successful user login, user can edit and save its profile information, change password and logout itself. If user is not able to login to the application i.e. forget the password, it can get password by clicking the link “Forgot Password?” in the login page itself. User is asked for the email id, which if valid and registered then password is sent to the email id. User can now login to the application by checking the mail and getting the password from there. If any new user wants to register itself in the application, there is a link “Register Here” for it. This link takes the user to the registration page where user can fill the required information and submit the information. User can change its password after successful login to the application by entering the old password and new password.

This Login & Registration example application provides:

  1. User Login
  2. User Registration
  3. Retrieve password to the registered email id
  4. Edit User Profile Information
  5. Change User Password
  6. User Logout

Application Development Steps:

To understand the application easily, we have divided the process in the following steps. These steps will let you understand the development of directory structure for the application, creating database structure, developing presentation layer through JSP, creating managed beans and running the application.

  1. Developing directory structure for the application
  2. Developing database for the application
  3. Creating configuration files
  4. Developing JSP files
  5. Creating managed beans
  6. Creating a properties file
  7. Registering managed bean and defining navigation rules
  8. Running the application

You can also download full source code for this application in zipped format. Unzip the source code and deployed it to the Tomcat server.
Download full Source Code

You can also download the database script to create the database required for the application. Execute the script and database will be created automatically.
Download Script for database

  Our example application uses:

  1. JSP pages for presentation purpose
  2. JavaBean to handle model data and
  3. Configuration files for defining managed bean, navigation rules, controller servlet.



JSF 2.0 Tutorial

Posted: May 7, 2012 in JSF + Hibernate

JavaServer Faces (JSF) 2.0, is a MVC web framework which focus on simplifies building user interfaces (comes with 100+ ready UI tags) for Java web application and make reusable UI component easy to implement. Unlike JSF 1.x, almost everything are declared in faces-config.xml, with JSF 2.0, you are allowed to use annotation to declared navigation, managed bean or CDI bean, which make your development more easier and faster.

In this tutorials, it provides many step by step examples and explanations on using JavaServer Faces (JSF) 2.0 framework.

Happy learning JSF 2.0 🙂

Quick Start

Some quick start examples for JSF 2.0

  • JSF 2.0 hello world example
    A JavaServer Faces (JSF) 2.0 hello world example, shows the JSF 2.0 dependencies, basic annotations and configurations. Let you have a quick idea about how JSF 2.0 look like, and also how it different from JSF 1.x.
  • JSF 2.0 + Ajax hello world example
    In JSF 2.0, coding Ajax is just like coding a normal HTML tag, it’s extremely easy. In this tutorial, you will restructure the last JSF 2.0 hello world example, so that, when the button is clicked, it will make an Ajax request instead of submitting the whole form.
  • How to make Eclipse IDE supports JSF 2.0
    Here’s a quick guide to show how to enable the JSF 2.0 features in Eclipse project.
  • Resources (library) in JSF 2.0
    In JSF 2.0, all your resources files like css, images or JavaScript, should put into a “resources” folder in the root of your web application. In JSF 2.0 terminology, all the sub-folder name of the “resources” folder is consider as a “library” in JSF 2.0 web application. Later, you can reference this “library” with JSF tag’s library attribute.

Managed Bean

About managed bean configuration and injection in JSF 2.0

  • Configure Managed Beans in JSF 2.0
    In JSF 2.0, Java bean that can be accessed from JSF page is called Managed Bean. The managed bean can be a normal Java bean, which contains the getter and setter methods, business logic or even a backing bean (a bean contains all the HTML form value).
  • Injecting Managed beans in JSF 2.0
    In JSF 2.0, a new @ManagedProperty annotation is used to dependency injection (DI) a managed bean into the property of another managed bean.


How navigation works in JSF 2.0

  • Implicit Navigation in JSF 2.0
    Now, JSF 2 come out a new “auto view page resolver” mechanism named “implicit navigation“, where you don’t need to declare the above navigation rule, instead, just put the “view name” in the action attribute and JSF will find the correct “view page” automatically.
  • Conditional Navigation Rule in JSF 2.0
    JSF 2 comes with a very flexible conditional navigation rule to solve the complex page navigation flow.
  • JSF “form-action” navigation rule example
    In JSF navigation rule, you may encounter a situation where two separate actions return a same “outcome” in a page. In this case, you can use “form-action” element to differentiate the two navigation cases.
  • JSF : Page Forward vs Page Redirect
    By default, JSF is perform a server page forward while navigating to another page. See following example to differentiate between the page forward and page redirect.

Resource Bundles

JSF’s message manipulation and internationalization.

  • JSF 2.0 and Resource Bundles example
    In this tutorial, we show you the use of resource bundle to display the messages in the JSF 2.0. For maintainability concern, it’s recommended to put all the messages in properties file, instead of hard-code the message in the page directly.
  • JSF 2 internationalization example
    JSF 2.0 internationalization or multiple languages example.

JSF Tag Library

Standard JSF 2 form’s tag component.

Table Manipulation

Add, update, delete and sorting data in via JSF’s dataTable.

Facelets Tags

Doing layout template with JSF 2.0 facelets tags.

Converters & Validation

Standard Convertors and validator tags in JSF 2.0

Composite Components

Reusable components in JSF 2.0

Event Handler

JSF 2 comes with many event handler to hijack the JSF’s life cycle.

Integrate with Other Frameworks

How to integrate JSF with external services.


Some Frequent ask questions in JSF 2.0

Common Errors

Some common error messages in JSF 2.0


Some useful reference site for further study on JSF 2.0

  1. JSF official Website
  2. The JSF application lifecycle
  3. Converter and Validation
  4. Communication in JSF


Reset password in SVN

Posted: May 3, 2012 in JSEE

The Problem

When you open a project from Subversion repository AnkhSVN will prompt you to authenticate (If you have turned on security in your subversion repository). Once you enter your username and password and check the save password it will not prompt again.

Now what if you change your password? I googled about this for two days but didn’t find any solution. Luckily today my boss found this.
The Solution

The authentication data is saved to the following directories


Deleting all the files inside these folders will solve the problem. After deleting these files AnkhSVN will prompt you for username and password once again.

I am currently writing a small Visual Studio Add-in that will help you clear these information from within Visual Studio.



JSF, update hibernate

Posted: May 1, 2012 in JSF + Hibernate

I can’t update my entity. I am using Hibernate and JSF 1.2 with Eclipse. This is my DAO:

public void updateTimesheet(Timesheet timesheet) {

And this is the bean:

public String doUpdate() {
    SessionFactory factory=new Configuration().configure().buildSessionFactory();
    Session session2= factory.getCurrentSession();
    timesheet=(Timesheet) dataModel.getRowData();
    return "ok";

And this is my getDataModel() method:

public DataModel getDataModel() {
    Session session2 = UtilHibernate.getSession();
    dataModel.setWrappedData(session2.createQuery("from Timesheet").list());
    return dataModel;

Uploading Files in NetBeans Visual Web JSF Applications


  1. Machine specifications used in this tutorial

  2. About the File Upload Component

  3. Creating a Page That Includes a File Upload Component

  4. Adding Code to Handle Image Uploads

  5. Testing the Application

  6. Doing More #1: Uploading a Text File

  7. Doing More #2: Modifying the Maximum File Upload Size

  8. Doing More #3: Saving the Uploaded Files to Other Locations

  9. A Different Folder in the Web Application

  10. A Known Directory on the Server

About the File Upload Component

The File Upload component enables users of your web application to locate a file on their system and upload that file to the server. This component is useful for collecting text files, image files, and other data. The contents of the uploaded file are stored together with some information about the file, including the file name, size, and MIME type (such as text/plain or image/jpeg).

The server holds the uploaded file in memory unless it exceeds 4096 bytes (4Kb), in which case the server holds the file contents in a temporary file. You can change this threshold by modifying the sizeThreshold parameter for the UploadFilter filter entry in the web application’s web.xml file. For more information on modifying the web.xml file, see the last section in this tutorial, Doing More: Modifying the Maximum File Upload Size. In cases where you want to retain the uploaded file, you have three choices:

  • Write the file to a location of your choice, as shown in this tutorial.
  • Create an UploadedFile property in a managed bean and set it to the component’s value before you exit the page (as in the button’s action method).
  • Save the file to a database that means in the table’s cell as other data or as normally done, save the file links in the database and the files to a location of your choice (under a folder).

By default, the File Upload component can handle files up to one megabyte in size. You can change the maximum file size by modifying the maxSize parameter for the UploadFilter filter entry in the application’s web.xml file, as described in the last section in this tutorial, Doing More: Modifying the Maximum File Upload Size.

Creating a Page That Includes a File Upload Component

First, you build a form that enables users to select a file to upload.

1.      Create a new Web Application project, name it FileUploadExample, and enable the Visual Web JavaServer Faces framework. The figure below shows the page that you will create in the steps that follow:

Let begin from scratch.

2.      From the Basic section of the Palette, drop a Label component on the page, type Choose a File to Upload: and press Enter.

3.      Drag a File Upload component onto the page and drop it underneath the Label component.

4.      Drag a Button component onto the page, type Upload File, and press Enter. In the Properties window, set the Button’s id property to uploadFileButton.

5.      Drag a Label component onto the page and set the text to File Name:

6.      Place a Static Text component to the right of the Label. In the Properties window, set the Static Text’s id property to fileNameStaticText.

7.      Drag another Label onto the page. Set the text of the Label to File Type:

8.      Place a Static Text component to the right of the new Label. Set the id of the Static Text to fileTypeStaticText.

9.      Drag another Label and Static Text pair onto the page. Set the text of the Label to File Size: and the id of the Static Text to fileSizeStaticText.

10. Place an Image component below the Static Text components.


11. Place a Message Group component below the Image component.

Adding Code to Handle Image Uploads

Now that you have the basic file upload form, you must add code to handle the file upload.

1.      Double-click the Upload File button to open the Java Editor and add the button’s event handler, uploadFileButton_action, to the page bean. Before adding code to this method, you define variables for storing the image file and add code to the init() and prerender() methods.

2.      Scroll up to the init() method and add the following two variables before the method.

Code Sample 1: Variables

private String realImageFilePath;

private static final String IMAGE_URL = “/resources/image-file”;

The variable realImageFilePath is the actual path and filename of the image file on the server. The IMAGE_URL variable is the logical path of the image file in the running web application. So these are a logical and physical path for the image file.

3.      Add the following lines of bold (shown in bold) at the end of the init method, but note that the code contains a Class Not Found error. You add import statements to fix these errors in next step. After inserting the code, you can press Ctrl-Shift-F to reformat the code.

Code Sample 2: init Method

public void init() {


     // Perform application initialization that must complete

     // *before* managed components are initialized

     // TODO – add your own initialization code here


     // Managed Component Initialization

     // Perform application initialization that must complete

     // *after* managed components are initialized

     // TODO – add your own initialization code here

     ServletContext theApplicationsServletContext =

         (ServletContext) this.getExternalContext().getContext();

     this.realImageFilePath = theApplicationsServletContext.getRealPath(IMAGE_URL);


This code converts IMAGE_URL into the real image file path so that the file can be written to the correct directory on the server.

4.      Scroll to the prerender method and add the following code:

Code Sample 3: prerender Method

public void prerender() {

   String uploadedFileName = (String) this.fileNameStaticText.getValue();

        if (uploadedFileName != null) {




If there is an image file to display, this code binds the file to the Image component. The image1 is the image component id.

5.      Add the following code to the uploadFileButton_action() method.

Code Sample 4: Code to Upload an Image File

public String uploadFileButton_action() {

        UploadedFile uploadedFile = fileUpload1.getUploadedFile();

        if( uploadedFile == null )

            return null;

        String uploadedFileName = uploadedFile.getOriginalName();

        // Some browsers return complete path name, some don’t

        // Make sure we only have the file name

        // First, try forward slash

        int index = uploadedFileName.lastIndexOf(‘/’);

        String justFileName;

        if (index >= 0)


            justFileName = uploadedFileName.substring( index + 1 );

        } else {

            // Try backslash

            index = uploadedFileName.lastIndexOf(‘\\’);

            if (index >= 0) {

                justFileName = uploadedFileName.substring( index + 1 );

            } else {

                // No forward or back slashes

                justFileName = uploadedFileName;




        Long uploadedFileSize = new Long(uploadedFile.getSize());


        String uploadedFileType = uploadedFile.getContentType();


        if ( uploadedFileType.equals(“image/jpeg”)

        || uploadedFileType.equals(“image/pjpeg”)

        || uploadedFileType.equals(“image/gif”)

        || uploadedFileType.equals(“image/png”)

        || uploadedFileType.equals(“image/x-png”)) {

            try {

                File file = new File(this.realImageFilePath);


            } catch (Exception ex) {

                error(“Cannot upload file: ” + justFileName);


        } else {

            error(“You must upload a JPEG, PJPEG, GIF, PNG, or X-PNG file. “);

            new File(this.realImageFilePath).delete();


   return null;


Correct all the formatted characters such as double and single quotes if needed. For each file, the program extracts the file name, size, and type from the UploadedFile object and binds them to the Static Text components. The program makes a key decision with all uploads: If the file is a JPEG, PJPEG, GIF, PNG, or X-PNG file, the program saves the uploaded file to the realImageFilePath variable. If the file is not a valid image file or if there are other problems uploading the file, the program deletes the image from the server and displays an error message.

6.      Right-click in the Java Editor and choose Fix Imports. In the Fix Import dialog box, ensure that java.io.File appears in the File dropdown list, and click OK. This action fixes the errors in the code.

Testing the Application

1.      Run the application by clicking the icon.

2.      Click Browse to navigate through your local drives and select an image file to upload. Then click the Upload File button.

3.       The following figure shows the application with an uploaded JPEG file. The image is stored in project-directory\FileUploadExample\build\web\resources.

In the browser address bar you can see something like the following address.


4.      Enter a text file in the File Upload component and click the Upload File button. Verify that the error message displays. Note: The rendering of the File Upload component can differ depending on the web browser. Be sure to test this component in the web browsers that you expect your users to use.

Doing More #1: Uploading a Text File

This section is a mini-tutorial on how to upload a text file. This example displays the file contents in a text area component, and the file name and size in a message group component. This example does not save the contents of the file. To do so, you must add code to save the file to disk, as shown in the previous example.

1.      Create a new Web Application project named UploadTextFile and enables the Visual Web JavaServer Faces framework.

2.      Drag a File Upload component onto the page.

3.      Add a Button component, a Text Area component, and a Message Group component.




Resize the Text Area component as needed.

4.      Double-click the Button component and add the following action code to the button1_action() method:

Code Sample 5: Code to Upload a Text File

public String button1_action() {

   UploadedFile uploadedFile = (UploadedFile) fileUpload1.getUploadedFile();

   if( uploadedFile == null )

       return null;

   info(“Uploaded file originally named ‘” + uploadedFile.getOriginalName() + “‘ of size ‘” +  uploadedFile.getSize() +  “‘”);


   return null;


5.      Press Ctrl-Shift-I or right-click and select Fix Imports to fix imports and automatically add the UploadedFile import statement.

6.      Run the application. The following figure shows a sample page with an uploaded text file.

7.      Click the Browse button to select a text file for uploading.

8.      Click the Button button.

Doing More #2: Modifying the Maximum File Upload Size

To enable the upload of a file greater than one megabyte (such as a large image file, ZIP, JAR, or executable file), you must modify the maxSize parameter for the UploadFilter filter in your application’s web.xml file.

1.      Open the Files window and expand project-name > web > WEB-INF.

2.      Right-click the web.xml node and choose Edit.

3.      In the XML editor, click the Filters button.

4.      Select the maxSize parameter for the UploadFilter, and click the Edit button.

5.      In the dialog box, set Param Value to the desired value, in this case we change 1MB to 10 MB and click OK.

6.      Note: For security reasons, do not set the maxSize parameter to a negative value, which indicates that there is no file size limit.

7.      Choose File > Save or click the Save All button to save your changes.

Note: If a user of your application tries to upload a file larger than the value of the maxSize parameter, the following exception is thrown and caught as a validation error:


The summary message displayed to users reads:

No file was uploaded

The detail message reads:

No file was uploaded. The specified file exceeds the maximum allowable size of 10000000 Mb

where 10000000 Mb is the value of maxSize.

Doing More #3: Saving the Uploaded Files to Other Locations

The previously completed tutorial shows how to upload a file to the web application’s /resources folder. What if you want to save the uploaded files elsewhere? Here are some alternatives.

A Different Folder in the Web Application

You can put the images in any directory in the web application (that is, any directory under the web application’s web directory). For example, you can create an upload/images subfolder under web and use the following code to store the images there:

Code Sample 6: Code to Upload a File to a Different Folder

String realPath = theApplicationsServletContext.getRealPath(“/upload/images”);

File file = new File(realPath + File.separatorChar + justFileName);

Be careful when putting the uploaded files in the web application because anyone can access the files by URL, such as:


You may want to put an index.html/index.htm/index.asp/index.php file (the first default web page) in the folder so that when user tries to go directly to the sub folder, the index.html file will be loaded. Then in the index.* file, create a link to the main application page. User will see something like the following where user can browse your web directory if there is no index file. Keep in mind that this folder has write permission for certain image file types.

Let modify the previous FileUploadExample. Create a /upload/images folder under the project’s web folder as shown below.

Re-open the project. Change the variables declaration to the following.

private String realPath;

private static final String IMAGE_URL = “/upload/images”;


Change the init() to the following. The realPath only hold the path and not the image file.

ServletContext theApplicationsServletContext=(ServletContext) this.getExternalContext().getContext();

       realPath = theApplicationsServletContext.getRealPath(IMAGE_URL);

Change the prerender to the following code. We display the image when user selects a file from the File Upload component. We read the file from the selected image file.

String uploadedFileName = (String) this.fileNameStaticText.getValue();

        if (uploadedFileName != null) {

              /* path + \ or \\ + filename */

            image1.setUrl(IMAGE_URL + File.separatorChar + uploadedFileName);


Finally change the following code in the uploadFileButton_action()

File file = new File(this.realImageFilePath);


File file = new File(realPath + File.separatorChar + justFileName);

Run your project.

Browse an image and click the Upload File button.

Try several more images and then verify the uploaded images in the upload/images folder.

A Known Directory on the Server

To store the images somewhere else on the server, you can use code such as the following:

Code Sample 7: Code to Upload a File to a Known Directory on a Server

File file = new File(“C:/upload/images” + File.separatorChar + justFileName);


Create upload/images folder on your C drive.

Change the following code in the uploadFileButton_action()

File file = new File(realPath + File.separatorChar + justFileName);


File file = new File(“C:/upload/images” + File.separatorChar + justFileName);

Run your project.

Select an image and click the Upload File button. Upload several more images.

Verify the uploaded files.

If you plan to deploy the application to different servers, you might use code like the following to ensure that the upload directory exists:

Code Sample 8: Code to Upload a File to Different Servers

File dir = new File(“C:/upload/images”);

if (! dir.exists())


File file = new File(dir.getCanonicalPath() + File.separatorChar + justFileName);


For more information about the File class, see Java File class.

An As-Yet Unknown Directory

Another alternative is to put the directory path in the deployment descriptor so that you can change the location dynamically.

1.      In the Files window, expand the web node and then expand WEB-INF. Double-click web.xml to open it.

2.      Click the General button and expand Context Parameters, and click the Add button.

3.      Set the following values, and then click OK.

Param Name: uploadDirectory (or whatever you want to name it)

Param Value: C:/upload/images (or whatever your path is)

4.      Close and save the web.xml file.

5.      Use the following code:

Code Sample 9: Code to Upload a File to an As-Yet Unknown Directory

String uploadDirectory = getExternalContext().getInitParameter(“uploadDirectory”);

File file = new File(uploadDirectory + File.separatorChar + justFileName);



Upload File in Richfaces

Posted: April 26, 2012 in JSEE

<ui:composition xmlns=”http://www.w3.org/1999/xhtml&#8221;

.top {
vertical-align: top;

.info {
height: 202px;
overflow: auto;

<h:panelGrid columns=”2″ columnClasses=”top,top”>
<rich:fileUpload fileUploadListener=”#{fileUploadBean.listener}”
acceptedTypes=”jpg, gif, png, bmp” allowFlash=”#{fileUploadBean.useFlash}”>
<a4j:support event=”onuploadcomplete” reRender=”info” />
<h:panelGroup id=”info”>
<rich:panel bodyClass=”info”>
<f:facet name=”header”>
<h:outputText value=”Uploaded Files Info” />
<h:outputText value=”No files currently uploaded”
rendered=”#{fileUploadBean.size==0}” />
<rich:dataGrid columns=”1″ value=”#{fileUploadBean.files}”
var=”file” rowKeyVar=”row”>
<rich:panel bodyClass=”rich-laguna-panel-no-header”>
<h:panelGrid columns=”2″>
<a4j:mediaOutput element=”img” mimeType=”#{file.mime}”
createContent=”#{fileUploadBean.paint}” value=”#{row}”
style=”width:100px; height:100px;” cacheable=”false”>
<f:param value=”#{fileUploadBean.timeStamp}” name=”time”/>
<h:panelGrid columns=”2″>
<h:outputText value=”File Name:” />
<h:outputText value=”#{file.name}” />
<h:outputText value=”File Length(bytes):” />
<h:outputText value=”#{file.length}” />
<rich:spacer height=”3″/>
<br />
<a4j:commandButton action=”#{fileUploadBean.clearUploadData}”
reRender=”info, upload” value=”Clear Uploaded Data”
rendered=”#{fileUploadBean.size>0}” />