Database Application using JSF (Login Application)

This example shows how to develop a simple User Login page by using JSF2, jdbc and MySQL. This application lets you validate user login credentials using jdbc and mysql database.

In this tutorial, JSF is used to create a simple login page where user will be authenticated based on database values.

In this example we have a login page. On Login button click, the username and password will be validated against DB values, if succeed then directed to success page otherwise ask to retry.I have used JDBC connectivity for MYSQL database.

Tools used :

  1. JSF 2
  2. Eclipse
  3. JDK 1.6
  4. Tomcat 6.0

Note:-If you have no idea about how to create JSF Application in eclipse then it is strongly recommended to complete Creating JavaServer Faces Application In Eclipse Tutorial before starting of this Project.

This example shows how to develop a simple User Login page by using JSF2, jdbc and MySQL. This application lets you validate user login credentials using jdbc and mysql database.

In this tutorial, JSF is used to create a simple login page where user will be authenticated based on database values.

In this example we have a login page. On Login button click, the username and password will be validated against DB values, if succeed then directed to success page otherwise ask to retry.I have used JDBC connectivity for MYSQL database.

Tools used :

  1. JSF 2
  2. Eclipse
  3. JDK 1.6
  4. Tomcat 6.0

Note:-If you have no idea about how to create JSF Application in eclipse then it is strongly recommended to complete Creating JavaServer Faces Application In Eclipse Tutorial before starting of this Project.




Step 1: Create Dynamic Web project

Open Eclipse and go to File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.

JSF Example

Provide the name of the project as JSFLoginExample . Once this is done, select the target runtime environment as Apache Tomcat v6.0. This is to run the project inside Eclipse environment. In configuration select JavaServer Faces v1.2 Project and press Next -> Next -> Next.

JSF Database Example

In next screen select Disable Library Configuration from drop down and click Finish.

JSF Database Example

Step 2: Add jar files to build path of the project

Copy all the required jar files shown bellow to the lib folder of the project directory and add all jar files to the build path of the project.

JSF Database Example


Step 3: Create JSP files

Create three JSP files: login.jsp, welcome.jsp and failure.jsp in WebContent folder.The login.jsp prompts the user to enter his/her name.After successful login user will be redirected to welcome.jsp . In the case of authentication failure user will be redirected to failure.jsp page.

login.jsp
<%@ page contentType="text/html"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<f:view>
<html>
<head><title>JSF Simple Login Example</title></head>
<body>
<h:form>
<table>
<tr>
<td><h:outputText value="Enter Login ID: " /></td>
<td><h:inputText id="userName" 
value="#{loginBean.userName}" />
</td>
</tr>
<tr>
<td><h:outputText value="Enter Password: " /></td>
<td><h:inputSecret id="password" 
value="#{loginBean.password}" />
</td>
</tr>
<tr>
<td> </td>
<td><h:commandButton value="Login" 
action="#{loginBean.checkValidUser}"/>
</td>
</tr>
</table>
</h:form>
</body>
</html>
</f:view>
success.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
    <head>       
        <title>Welcome Page</title>
    </head>
    <body>
        <h2>Login Successful!</h2>
    </body>
</html>
failure.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Error Page</title>
    </head>
    <link rel="stylesheet" type="text/css" href="CSS/style.css">
    <body>
 
        <h2> Login Failed! </h2>
    </body>
</html>

Step 4 : Create JSF Managed Bean

A Managed Bean is a regular Java Bean class, registered with JSF. In other words, Managed Bean is a java bean, managed by the JSF framework.From JSF 2.0 and onwards, we can declare a managed bean, just by using the annotation @ManagedBean.

Create a java class LoginBean inside "com.javawebtutor.jsf" package and add bellow line of code into this class.

package com.javawebtutor.jsf;

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

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

 
@ManagedBean(name="loginBean")
@SessionScoped
public class LoginBean {
    private String userName;
    private String password;
    private String dbuserName;
 
    private String dbpassword;
    Connection connection;
    Statement statement;
    ResultSet resultSet;
    String SQL;
    
 
    public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getDbuserName() {
		return dbuserName;
	}

	public void setDbuserName(String dbuserName) {
		this.dbuserName = dbuserName;
	}

	public String getDbpassword() {
		return dbpassword;
	}

	public void setDbpassword(String dbpassword) {
		this.dbpassword = dbpassword;
	}

	public void dbData(String userName)
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jwt","root","mukesh");
            statement = connection.createStatement();
            SQL = "Select * from USER_DETAIL where username like ('" + userName +"')";
            resultSet = statement.executeQuery(SQL);
            resultSet.next();
            dbuserName = resultSet.getString(1).toString();
            dbpassword = resultSet.getString(2).toString();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            System.out.println("Exception Occured in the process :" + ex);
        }
    }
    
    public String checkValidUser()
    {
        dbData(userName);
 
        if(userName.equalsIgnoreCase(dbuserName))
        {
 
            if(password.equals(dbpassword))
                return "success";
            else
            {
                return "failure";
            }
        }
        else
        {
            return "failure";
        }
    }
}

Note:- In JSF 1.x, you had to declare this beans in the faces-config.xml, but this is no longer required in JSF 2.0. We declare this beans using annotation.



Step 5 : Update Configuration File(faces-config.xml)

Jsf looks for faces-config.xml in classpath and loads the configuration defined from here. Here we have defined managed bean (the backing bean), and navigation rule.Open faces-config.xml from WebContent -> WEB-INF folder and following code into this file.

faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">

	<navigation-rule>
		<description>Loging Page</description>
		<from-view-id>/login.jsp</from-view-id>
		<navigation-case>
			<from-action>#{loginBean.checkValidUser}</from-action>
			<from-outcome>success</from-outcome>
			<to-view-id>/success.jsp</to-view-id>
		</navigation-case>
		<navigation-case>
			<from-action>#{loginBean.checkValidUser}</from-action>
			<from-outcome>failure</from-outcome>
			<to-view-id>/failure.jsp</to-view-id>
		</navigation-case>

	</navigation-rule>

</faces-config>

Step 6 : JSF 2.0 Serlvet Configuration

In this step we will configure JSF via the web.xml file which is found under src/main/webapp/WEB-INF.

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>JSFLoginExample</display-name>
	<welcome-file-list>

		<welcome-file>login.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>
</web-app>

Final Structure Of Project

Final structure of project is shown below:

JSF Database Example

Step 7 : Create database Table to hold data of user

Open mysql and execute following sql query to create USER_DETAIL table.

CREATE TABLE `USER_DETAIL` (  
`username` varchar(30) NOT NULL, 
`password` varchar(30) NOT NULL 
);

Insert sample data for our Application.

insert into USER_DETAIL values("mukesh","kumar");
insert into USER_DETAIL values("ravi","raj");

Step 8 : Run the Application

Right Click on the login.jsp file and select Run as --> Run on Server

JSF Database Example

In next screen select choose an existing server and select tomcat v6.0 as shown below and click Next.

JSF Database Example

Now select JSFLoginExample from Add and Remove Screen and click Finish.

JSF Database Example


Output :

1 : Login Screen

JSF Database Example

2 : Successful Login Screen

If user will provide correct value he will navigate to success.jsp page

JSF Database Example

3 : Login Failure Screen

If user will provide incorrect value he will navigate to failure.jsp page

JSF Database Example

You can download the source code of the example by clicking on the Download link below.

Source (Developed in Eclipse) : Download



comments powered by Disqus