User Registration Application in JSF

Noor ul Huda
This tutorial is designed basically for beginners of JSF.

From this post, one can easily understand , how to save values in database using JSF components.

Hope this 'll help you...:)

1. Create New Dynamic Web Project in Eclipse IDE, like this:

2. Click Next and you 'll see like that:

 

 

3. Now click on managed libarary. Add jar files for JSF configuration from here: (JSF jars)

 

 

4. Now Add New Class in Project src folder like:

 

 

Classes Names and packages names:

1- UserRegisterClass & com.jsf.user

2 - DatabaseClass & com.jsf.db

* Code for UserRegisterClass.java:

package com.jsf.user;

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

import com.jsf.db.DatabaseClass;

@ManagedBean(name="user")
@SessionScoped
public class UserRegisterClass {
   
    public UserRegisterClass() {
        System.out.println("-----------------------------------------------------");
        System.out.println("-----UserRegister Default Constructor Called---------");
        System.out.println("-----------------------------------------------------");
    }

    /* ---------------------- Class Variables ---------------------- */
    private String name;
    private String password;
    private String email;
    private String address;
    private String contact;
    DatabaseClass obj=new DatabaseClass();
   
    /* ---------------------- Getters and Setters ---------------------- */
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getContact() {
        return contact;
    }
    public void setContact(String contact) {
        this.contact = contact;
    }
   
    /* ---------------------- Method call on Register Button ---------------------- */
   
    public String register()
    {
        System.out.println("----------- register Method Called ---------");
        try {
            obj.dbRegister(name, password, email, contact, address);
           
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "user?faces-redirect=true";
    }

* Code for DatabaseClass.java:

package com.jsf.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


public class DatabaseClass {

    public DatabaseClass() {
    System.out.println("-----------------------------------------------------");
    System.out.println("-----------Database Class Constructor Called---------");
    System.out.println("-----------------------------------------------------");
    }
   
    /* ------------------------- Class Variables -----------------------------*/
    Connection connection = null;
    Statement statement =null;

    /* ------------------------- Database Connection Method -----------------------------*/
    public Connection getMySqlConnection() throws SQLException, ClassNotFoundException
    {
         
         
          String driver = "com.mysql.jdbc.Driver";
          String userName = "root";
          String password = "root";
          String dbname="test";
          Class.forName(driver);
          String url = "jdbc:mysql://localhost:3306/"+dbname;
          connection = DriverManager.getConnection(url, userName, password);
          System.out.println("----------Connection URL: "+connection+"-------");
        return connection;
       
    }
   
    /* ------------------------- dbRegister Method -----------------------------*/
    public void dbRegister(String name, String password, String email, String contact, String address)
    {
        try {
            String query="INSERT INTO User(Name,Password,Email,Contactno,Address)" +
                " VALUES('"+name+"','"+password+"','"+email+"','"+contact+"','"+address+"')";
            connection=getMySqlConnection();
            statement=connection.createStatement();
            statement.executeUpdate(query);
            System.out.println("-------- Query :"+query+" -------------------");
            System.out.println("-------- Registration Done in User Table -------------------");
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

5. In JSF, for validation of fields in form. One can use validators, i also used validators on registration page.

For validators, create new package name : com.jsf.validator
In this package, create three new classes for validators.
1- nameValidator
2- EmailValidator
3- contactValidtor
  

* Code for nameValidator.java:

package com.jsf.validator;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.component.html.HtmlInputTextarea;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
/*
 * @ By Noor-ul-Huda
 * 
 */
@FacesValidator("nameValidator")
public class nameValidator implements Validator {
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
String compValue = null;
boolean flag = false;
if (component != null && component instanceof HtmlInputText) {
compValue = (String) ((HtmlInputText) component).getSubmittedValue();
} else if (component != null && component instanceof HtmlInputTextarea) {
compValue = (String) ((HtmlInputTextarea) component).getSubmittedValue();
}
if (compValue != null && !compValue.equalsIgnoreCase("")) {
flag = compValue.matches("[ _]*[a-zA-Z0-9_-]*");
}
if (!flag) {
if (component instanceof HtmlInputText) {
((HtmlInputText) component).setTitle("No special symbols are allowed here");
} else if (component instanceof HtmlInputTextarea) {
((HtmlInputTextarea) component).setTitle("No special symbols are allowed here");
} else if (component instanceof HtmlSelectOneMenu) {
((HtmlSelectOneMenu) component).setTitle("Page got some un-conditional Data");
}
throw new ValidatorException(new FacesMessage("No special symbols are allowed"));
}
}
}

* Code for EmailValidator.java:

package com.jsf.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/*
 * @ By Noor-ul-Huda
 * 
 */


@FacesValidator("emailValidator")
public class EmailValidator implements Validator{

    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\." +
            "[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*" +
            "(\\.[A-Za-z]{2,})$";

    private Pattern pattern;
    private Matcher matcher;

    public EmailValidator(){
          pattern = Pattern.compile(EMAIL_PATTERN);
    }

    @Override
    public void validate(FacesContext context, UIComponent component,
            Object value) throws ValidatorException {

        matcher = pattern.matcher(value.toString());
        if(!matcher.matches()){

            FacesMessage msg =
                new FacesMessage("E-mail validation failed.",
                        "Enter E-mail like: example@yahoo.com");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);

        }

    }
}

* Code for contactValidator.java:

 package com.jsf.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/*
 * @ By Noor-ul-Huda
 *
 */

@FacesValidator("contactValidator")
public class contactValidator implements Validator {
    private static final String Phone_PATTERN = "[0-9]{4}[-][0-9]{7}";
    private Pattern pattern;
    private Matcher matcher;

    public contactValidator() {
        pattern = Pattern.compile(Phone_PATTERN);
    }

    @Override

    public void validate(FacesContext context, UIComponent component,
            Object value) throws ValidatorException {

        matcher = pattern.matcher(value.toString());
        if (!matcher.matches()) {

            FacesMessage msg = new FacesMessage("MobileNo. validation failed.",
                    "Enter like:(0300-1234567)");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);

        }

    }
}

Now src folder look like this, after creating above classes and their packages. 


 

6. Now Add new HTML file like this:

 




Create two new HTML files and save with .xhtml extension:
1- register.xhtml
2- user.xhtml

* register.xhtml File:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
<h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <title>.:: User Registration Page ::.</title>
</h:head>
<body>
<h:form>
    <br />
    <h2 align="center">User Registration Form</h2>
    <table align="center" border="1" width="50%" cellpadding="3">
        <tr>
            <td>Name:</td>
            <td><h:inputText id="name" value="#{user.name}" required="true"
                requiredMessage="Enter name!" label="name" maxlength="20"
                validator="nameValidator" /></td>
            <td><h:message for="name" style="color:red;" /></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><h:inputSecret id="password" value="#{user.password}"
                required="true" requiredMessage="Enter Password!" label="password"
                maxlength="15" redisplay="true" /></td>
            <td><h:message for="password" style="color:red;" /></td>
        </tr>
        <tr>
            <td>Email:</td>
            <td><h:inputText id="email" value="#{user.email}"
                required="true" requiredMessage="Enter Email!" label="email"
                maxlength="50" validator="emailValidator" /></td>
            <td><h:message for="email" style="color:red;" /></td>
        </tr>
        <tr>
            <td>Contact no:</td>
            <td><h:inputText id="contact" value="#{user.contact}"
                required="true" requiredMessage="Enter Contact no!" label="contact"
                maxlength="12" validator="contactValidator" /></td>
            <td><h:message for="contact" style="color:red;" /></td>
        </tr>
        <tr>
            <td>Address:</td>
            <td><h:inputTextarea id="address" value="#{user.address}"
                required="true" requiredMessage="Enter Adrdess!" label="address"
                maxlength="100" cols="15" /></td>
            <td><h:message for="address" style="color:red;" /></td>
        </tr>

        <tr>
            <td colspan="3" align="center"><h:commandButton id="btn"
                value="Register" type="submit" action="#{user.register}" /></td>
        </tr>
    </table>
</h:form>
</body>
</html>

* user.xhtml File:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
<h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <title>.:: User Registration Page ::.</title>
</h:head>
<body>
<h:form>
    <br />
    <h3 align="center">User Registered Successfully!</h3>
    <table align="center" border="2" width="40%" cellpadding="5">
        <tr>
            <td style="font-weight: bold;" width="25%">Name:</td>
            <td><h:outputText id="name" value="#{user.name}" /></td>

        </tr>
        <tr>
            <td style="font-weight: bold;">Password:</td>
            <td><h:outputText id="password" value="#{user.password}" /></td>

        </tr>
        <tr>
            <td style="font-weight: bold;">Email:</td>
            <td><h:outputText id="email" value="#{user.email}" /></td>

        </tr>
        <tr>
            <td style="font-weight: bold;">Contact no:</td>
            <td><h:outputText id="contact" value="#{user.contact}" /></td>

        </tr>
        <tr>
            <td style="font-weight: bold;">Address:</td>
            <td><h:outputText id="address" value="#{user.address}" /></td>

        </tr>


    </table>
</h:form>
</body>
</html>

7. Now Add mysql jar file for database connection. In Webcontent > WEB-INF > lib folder, like:

 

 mysql jar file download from here (mysqlconnector.jar)

 

8. Now Project structure looks like this:

 

9. I used mySQL database for this application. 

Create database name: test and run script file: (user.sql) , for creating new table in database. I did this all for inserting record of new user after registration. Table looks like:

10.  Now Run this application via glassfish server version 3, you 'll get output screen like this:

 

11.  Now Click on Register button leaving all fields empty. You 'll get errors because of JSF validation, and screen looks like this:

 

 

12.  Now enter values in all fields, except name. Enter special characters in name field like : user@@.  Then click on register button, it 'll show output like this :

13. Now Enter valid value in name field and enter invalid email address, it gives output like this:

14. Now enter valid values in all fields excluding contactno , enter invalid value in this field. It 'll looks like this:

 

15. Now enter valid values in all fields and click register button, you 'll get new page with output like this :

 

This screen show all values which u filled in register.xhtml page, and user record also insert in database. That's all about registration of new user by using jsf components.

I upload war file of this application. By running that war file, one 'll get output like above screens. Download that war file from here. (User_registartion.war)

 

I hope you 'll enjoy this application...:) Must Give ur feedback about this post.

Post a Comment

2Comments
  1. As'salam O Alaikum !
    mein ne recently apke blog ko join kia hai q k muje yhan per wo cheez mili hai jo muje chahiye, Information about XML and PHP. kya apko PHP Language aati hai ?

    ReplyDelete
    Replies
    1. Walikum Salam, yes i m Java + PHP developer, as u can see posts of Java and PHP in my Blog.

      Delete
Post a Comment

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !