Simple Database Application with JSF (User Login)

Here I am not going to show you step wise operation but I am only providing you the source code for each file that I have implemented for a Login application based on database. I hope you can easily follow these instructions after going through first three tutorials that I had published in previous post .

Here in this example we are having a login page. On Login button click, the username and password will get checked for login, if succeed then directed to success page otherwise ask to retry. And yes, I have used JDBC connectivity for MYSQL database. and I have used Netbeans IDE for this application.

Here we have files:

Inside Web Pages directory

login.jsp            -for login interface
login_fail.jsp     -for re-login interface
success.jsp        -page after successful login

Inside WEB-INF directory

faces-config.xml  – JSF configuration file

Inside beans package

login_bean.java  – here we define the connectivity and logic of the program.

Inside messages package

message.property  -It holds the message for validation.

Inside CSS directory

style.css  -CSS styles for the given JSP pages.

Database -db_jsf
Table – tbl_users
Fields -ID, UName, PWord

login.jsp

<%--
    Document   : Login
    Created on : Jan 18, 2010, 7:58:03 PM
    Author     : Prashant
--%>

<%@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>LOGIN</title>
    </head>
    <link rel="stylesheet" type="text/css" href="CSS/style.css">
    <body>

        <f:view>
            <h:form id="login_frm">
                <h2>Login Please:</h2>
                <table width="250" border="0" cellspacing="0" cellpadding="2">
                  <tr>
                      <td colspan="2">
                            <h:message for="username" styleClass="errorMsg"/><br>
                            <h:message for="password" styleClass="errorMsg"/>
                        </td>
                  </tr>
                  <tr>
                    <td><h:outputText value="Username : "/></td>
                    <td><h:inputText id="username" value="#{login_bean.username}" required="true" styleClass="input_text"/></td>
                  </tr>
                  <tr>
                    <td><h:outputText value="Password : "/></td>
                    <td><h:inputSecret id="password" value="#{login_bean.password}" required="true" styleClass="input_text"/></td>
                  </tr>
                  <tr>
                      <td colspan="2" align="center">
                          <h:commandButton action="#{login_bean.checkValidUser}" value="Login" type="submit"/></td>
                  </tr>
                </table>
            </h:form>
        </f:view>
    </body>
</html>

success.jsp

<%--
    Document   : success
    Created on : Jan 18, 2010, 9:35:40 PM
    Author     : Prashant
--%>

<%@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>JSP Page</title>
    </head>
    <body>
        <f:view>
            <h:form>
                <h2>Hello <h:outputText value="#{login_bean.username}"/>, you are successfully login.</h2>
            </h:form>
        </f:view>
    </body>
</html>

login_fail.jsp

<%--
    Document   : Login
    Created on : Jan 18, 2010, 7:58:03 PM
    Author     : Prashant
--%>

<%@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>LOGIN</title>
    </head>
    <link rel="stylesheet" type="text/css" href="CSS/style.css">
    <body>

        <f:view>
            <h:form id="login_frm">
                <h2>Login Please:</h2>
                <table width="250" border="0" cellspacing="0" cellpadding="2">
                  <tr>
                      <td colspan="2">
                            Incorrect Username or Password!!<br>
                            <h:message for="username" styleClass="errorMsg"/><br>
                            <h:message for="password" styleClass="errorMsg"/>
                        </td>
                  </tr>
                  <tr>
                    <td><h:outputText value="Username : "/></td>
                    <td><h:inputText id="username" value="#{login_bean.username}" required="true" styleClass="input_text"/></td>
                  </tr>
                  <tr>
                    <td><h:outputText value="Password : "/></td>
                    <td><h:inputSecret id="password" value="#{login_bean.password}" required="true" styleClass="input_text"/></td>
                  </tr>
                  <tr>
                      <td colspan="2" align="center">
                          <h:commandButton action="#{login_bean.checkValidUser}" value="Login" type="submit"/></td>
                  </tr>
                </table>
            </h:form>
        </f:view>
    </body>
</html>

faces-config.xml

<?xml version='1.0' encoding='UTF-8'?>

<!-- =========== FULL CONFIGURATION FILE ==================== -->

<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">

        <managed-bean>
            <managed-bean-name>login_bean</managed-bean-name>
            <managed-bean-class>beans.login_bean</managed-bean-class>
            <managed-bean-scope>request</managed-bean-scope>
        </managed-bean>
    <navigation-rule>
        <description>Loging Page</description>
        <from-view-id>/login.jsp</from-view-id>
        <navigation-case>
            <from-action>#{login_bean.checkValidUser}</from-action>
            <from-outcome>valid</from-outcome>
            <to-view-id>/success.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{login_bean.checkValidUser}</from-action>
            <from-outcome>invalid</from-outcome>
            <to-view-id>/login_fail.jsp</to-view-id>
        </navigation-case>

    </navigation-rule>
    <navigation-rule>
        <description>ReLoging Page</description>
        <from-view-id>/login_fail.jsp</from-view-id>
        <navigation-case>
            <from-action>#{login_bean.checkValidUser}</from-action>
            <from-outcome>valid</from-outcome>
            <to-view-id>/success.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{login_bean.checkValidUser}</from-action>
            <from-outcome>invalid</from-outcome>
            <to-view-id>/login_fail.jsp</to-view-id>
        </navigation-case>

    </navigation-rule>
    <application>
        <message-bundle>messages.message</message-bundle>
    </application>
</faces-config>

login_bean.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

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

/**
 *
 * @author Prashant
 */
import java.sql.*;
import java.util.*;

@ManagedBean(name="login_bean")
@RequestScoped
public class login_bean {
    private String username;
    private String password;
    private String dbusername;

    public String getDbpassword() {
        return dbpassword;
    }
    public String getDbusername() {
        return dbusername;
    }

    private String dbpassword;
    Connection con;
    Statement ps;
    ResultSet rs;
    String SQL_Str;

    public void dbData(String UName)
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_jsf","root","root");
            ps = con.createStatement();
            SQL_Str="Select * from tbl_users where UName like ('" + UName +"')";
            rs=ps.executeQuery(SQL_Str);
            rs.next();
            dbusername=rs.getString(2).toString();
            dbpassword=rs.getString(3).toString();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            System.out.println("Exception Occur :" + ex);
        }
    }
    public String getPassword() {
        return password;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    public String checkValidUser()
    {
        dbData(username);

        if(username.equalsIgnoreCase(dbusername))
        {

            if(password.equals(dbpassword))
                return "valid";
            else
            {
                return "invalid";
            }
        }
        else
        {
            return "invalid";
        }
    }
}

message.property

# To change this template, choose Tools | Templates
# and open the template in the editor.

javax.faces.component.UIInput.REQUIRED=Please enter a value for this field.

style.css

/*
    Document   : style
    Created on : Jan 18, 2010, 8:29:32 PM
    Author     : Prashant
    Description:
        Purpose of the stylesheet follows.
*/

/*
   TODO customize this sample style
   Syntax recommendation http://www.w3.org/TR/REC-CSS2/
*/

root {
    display: block;
}
body
{
    font-family: sans-serif;
    font-size: 10px;
    color: #000000;
}
h2
{
    font-size: 16px;
    color: #3d2dff;
    font-family:serif;
}
.errorMsg
{
    font-size: 12px;
    font-family: serif;
    font-weight: bold;
    color: #FF0000;
    padding: 5px;
}

.input_text{
	font-family:Arial, Helvetica, sans-serif;
	font-size:10px;
	border:1px solid #FF7C08;
}

Snaps:

Table: tbl_users

Login Page

Unsuccessful Login

Successful Login

If you have any comment or suggestion on this post, please do comment me.

ref: http://www.roseindia.net/jsf/JSFLoginApplication.shtml

[/sourcecode][/sourcode]

Some useful resources for JSF

Actually I am very new for Framework. Previously whenever I worked, i did with PHP, JSP were everything come as programming logic. But here in JSF I am finding the things little different. It is easy to use but little tough to learn. I am finding very less resources. Any way I am still searching for some useful resources, so that i can do everything that I had done with PHP and JSP or more than that.

Here i found some useful tutorial in netbeans site, after following these tutorials I got some concept of JSF. I hope this links may be helpful for those beginner who are just starting JSP.

http://netbeans.org/kb/67/web/jastrologer-intro.html
http://netbeans.org/kb/67/web/jastrologer-validate.html
http://netbeans.org/kb/67/web/jastrologer-jsfformtags.html

http://www.jsftutorials.net/

For Database Operation I would like to suggest you these links:

http://balusc.blogspot.com/2008/07/dao-tutorial-use-in-jsf.html#FacesConfigurationXml
http://www.javaguicodexample.com/javavisualwebdatabaseappdev.html

Here is one of the very useful tutorial, which made my day

http://www.roseindia.net/jsf/

Please do send some more links if you know.

Begining With JSF

I began JSF from just yesterday. After various suggestion I have selected Netbeans for JSF. So here are some steps to begin with JSF in Netbeans. I hope it will be helpful to you. (Download Netbeans from here)

Step 1:

File > New Project

Step 2:

From the New Project dialogue box, Select Web from Category and Web Application From Rejects, then click Next button.

Step 3:

Provide the Project Name and Location for the project, then click Next button.

Step 4:

Select server, As in Netbeans, if you have GlassFish, you will get GlassFish as default. Otherwise you have to click on Add button to add Tomcat. Then click on Next button.

Step 5:

Here we select the Framework for the project, and we have to select JavaServer Faces. Then click on finish.

Step 6:

Project will get created. Press CTRL+1 to go to Project tab. Open the project list and right click on WebPages and create new JSP file with name “HelloWorld”.

Step 7:

Code in the page will looks like this.

<%--
 Document   : HelloWorld
 Created on : Jan 11, 2010, 10:43:11 AM
 Author     : prashant
--%>

<%@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">

<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>JSP Page</title>
 </head>
 <body>
 <h1>Hello World!</h1>
 </body>
</html>

Step 8:

To add JavaServer Faces components in JSP pages, you need to give your pages access to the two standard tag libraries, the HTML component tag library and the core tag library using taglib declarations. So, add these lines before <html> tag.

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

Step 9:

Add these lines to the body part.


<f:view>

<h:outputText lang="en_US" value="Hello World"/>

</f:view>

Step 10:

Press Shift+F6 to run.