A simple JSF example with AJAX in Netbeans

Today, I was trying to do Ajax on JSF. As it was my first AJAX in JSF, I had struggled little bit. But finally I got output as I had needed.

In this application, I have given two dropdown list related to mobile. In which, one will be company name and another mobile model. As the company will be selected from company dropdown list, the content of the model dropdown will get change according to the selected company.

Here is the procedure, that can be followed to complete this example in Netbeans(6.9).

Create a new project as Web Application

File > New Project >Java Web > Web Application

Provide a project name

Select Web Server for the application

Select JSF as a Framework

To create a JSF Manage Bean, right Click on the Project name on project pan.
New > Other…  > Java Server Faces > JSF Manage Bean

Provide the Class name (JsfBean) and package name (beans)

Now the JsfBean.java contains the following code, which provide the Item list for the dropdown list, and the setModel(AjaxBehaviorEvent evt) method is called using Ajax on the Company dropdown list, which will change the content of the model drop down list according to the selected item in the company name.

/*******JsfBean.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;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.model.SelectItem;

/**
 *
 * @author Prashant
 */
@ManagedBean
@RequestScoped
public class JsfBean {

    /** Creates a new instance of JsfBean */
    private SelectItem[] company=new SelectItem[]{
        new SelectItem("nokia", "Nokia"),
        new SelectItem("samsung", "Samsung"),
        new SelectItem("sony ericson", "Sony Ericsson"),
        new SelectItem("black berry", "Black Berry")
    };
    private SelectItem[] nokia=new SelectItem[]{
        new SelectItem("8800 Carbon","8800 Carbon"),
        new SelectItem("E90 Communicator", "E90 Communicator"),
        new SelectItem("N97", "N97"),
        new SelectItem("N96", "N96"),
        new SelectItem("N95", "N95"),
        new SelectItem("6260 Slide", "6260 Slide"),
        new SelectItem("5800 Express music", "5800 Express music"),
        new SelectItem("N73 Music Edition", "N73 Music Edition")
    };
    private SelectItem[] samsung=new SelectItem[]{
        new SelectItem("OMNIA i900","OMNIA i900"),
        new SelectItem("S8330 Ultra TOUCH", "S8330 Ultra TOUCH"),
        new SelectItem("M8800 Pixon", "M8800 Pixon"),
        new SelectItem("Jet S8003", "Jet S8003"),
        new SelectItem("Jet U900 Soul", "U900 Soul"),
        new SelectItem("DJ M7603", "DJ M7603"),
        new SelectItem("U800 Soul B", "U800 Soul B"),
        new SelectItem("Beat M3510", "Beat M3510"),
        new SelectItem("D780", "D780"),
        new SelectItem("E251", "E251"),
    };
    private SelectItem[] sony=new SelectItem[]{
        new SelectItem("Xperia X1","Xperia X1"),
        new SelectItem("C905", "C905"),
        new SelectItem("W995", "W995"),
        new SelectItem("W980i", "W980i"),
        new SelectItem("K850i", "K850i"),
        new SelectItem("C902", "C902"),
        new SelectItem("W705", "W705")
    };
    private SelectItem[] blackberry=new SelectItem[]{
        new SelectItem("Bold 9000","Bold 9000"),
        new SelectItem("8820", "8820"),
        new SelectItem("8830", "8830"),
        new SelectItem("8800", "8800"),
        new SelectItem("Curve 8900", "Curve 8900"),
        new SelectItem("Curve 8310", "Curve 8310"),
        new SelectItem("Pearl 8110", "Pearl 8110"),
        new SelectItem("Pearl Flip 8220", "Pearl Flip 8220")
    };
    private SelectItem model[]=nokia;
    private String company_name="company_name";
    private String model_no;
    public JsfBean() {

    }

    public SelectItem[] getCompany() {
        return company;
    }

    public void setCompany(SelectItem[] company) {
        this.company = company;
    }

    public String getCompany_name() {
        return company_name;
    }

    public void setCompany_name(String company_name) {
        this.company_name = company_name;
    }

    public String getModel_no() {
        return model_no;
    }

    public void setModel_no(String model_no) {
        this.model_no = model_no;
    }

    public SelectItem[] getNokia() {
        return nokia;
    }

    public void setNokia(SelectItem[] nokia) {
        this.nokia = nokia;
    }

    public SelectItem[] getSamsung() {
        return samsung;
    }

    public void setSamsung(SelectItem[] samsung) {
        this.samsung = samsung;
    }

    public SelectItem[] getModel() {
       //
       // this.model = nokia;
        return model;
    }

    public void setModel(AjaxBehaviorEvent evt) {
       if(company_name.equalsIgnoreCase("nokia"))
            this.model =nokia;
       else if(company_name.equalsIgnoreCase("samsung"))
           this.model =samsung;
       else if(company_name.equalsIgnoreCase("sony ericson"))
           this.model =sony;
       else if(company_name.equalsIgnoreCase("black berry"))
           this.model =blackberry;
    }

}

The index.xhtml will contains following tags to display two dropdown list and to link then using Ajax.

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- index.xhtml -->
<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>
        <title>JSF AJAX</title>
    </h:head>
    <h:body>
        <h3>Select Mobile</h3>
            <h:form>
                Company : <h:selectOneMenu value="#{jsfBean.company_name}">
                        <f:selectItems value="#{jsfBean.company}"/>
                        <f:ajax event="change" render="model" listener="#{jsfBean.setModel}" />
                    </h:selectOneMenu><br></br><br></br>

                Model :
                <h:selectOneMenu value="#{jsfBean.model_no}" id="model" style="width: 120px;">
                    <f:selectItems value="#{jsfBean.model}"/>
                </h:selectOneMenu>
            </h:form>

    </h:body>
</html>

This application can be more effective if the given application can be implemented with database, where the dropdown lists will be loaded from database records.

Outputs :

/*
* 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;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.model.SelectItem;

/**
*
* @author Prashant
*/
@ManagedBean
@RequestScoped
public class JsfBean {

/** Creates a new instance of JsfBean */
private SelectItem[] company=new SelectItem[]{
new SelectItem(“nokia”, “Nokia”),
new SelectItem(“samsung”, “Samsung”),
new SelectItem(“sony ericson”, “Sony Ericsson”),
new SelectItem(“black berry”, “Black Berry”)
};
private SelectItem[] nokia=new SelectItem[]{
new SelectItem(“8800 Carbon”,”8800 Carbon”),
new SelectItem(“E90 Communicator”, “E90 Communicator”),
new SelectItem(“N97”, “N97”),
new SelectItem(“N96”, “N96”),
new SelectItem(“N95”, “N95”),
new SelectItem(“6260 Slide”, “6260 Slide”),
new SelectItem(“5800 Express music”, “5800 Express music”),
new SelectItem(“N73 Music Edition”, “N73 Music Edition”)
};
private SelectItem[] samsung=new SelectItem[]{
new SelectItem(“OMNIA i900″,”OMNIA i900”),
new SelectItem(“S8330 Ultra TOUCH”, “S8330 Ultra TOUCH”),
new SelectItem(“M8800 Pixon”, “M8800 Pixon”),
new SelectItem(“Jet S8003”, “Jet S8003”),
new SelectItem(“Jet U900 Soul”, “U900 Soul”),
new SelectItem(“DJ M7603”, “DJ M7603”),
new SelectItem(“U800 Soul B”, “U800 Soul B”),
new SelectItem(“Beat M3510”, “Beat M3510”),
new SelectItem(“D780”, “D780”),
new SelectItem(“E251”, “E251”),
};
private SelectItem[] sony=new SelectItem[]{
new SelectItem(“Xperia X1″,”Xperia X1”),
new SelectItem(“C905”, “C905”),
new SelectItem(“W995”, “W995”),
new SelectItem(“W980i”, “W980i”),
new SelectItem(“K850i”, “K850i”),
new SelectItem(“C902”, “C902”),
new SelectItem(“W705”, “W705”)
};
private SelectItem[] blackberry=new SelectItem[]{
new SelectItem(“Bold 9000″,”Bold 9000”),
new SelectItem(“8820”, “8820”),
new SelectItem(“8830”, “8830”),
new SelectItem(“8800”, “8800”),
new SelectItem(“Curve 8900”, “Curve 8900”),
new SelectItem(“Curve 8310”, “Curve 8310”),
new SelectItem(“Pearl 8110”, “Pearl 8110”),
new SelectItem(“Pearl Flip 8220”, “Pearl Flip 8220″)
};
private SelectItem model[]=nokia;
private String company_name=”company_name”;
private String model_no;
public JsfBean() {

}

public SelectItem[] getCompany() {
return company;
}

public void setCompany(SelectItem[] company) {
this.company = company;
}

public String getCompany_name() {
return company_name;
}

public void setCompany_name(String company_name) {
this.company_name = company_name;
}

public String getModel_no() {
return model_no;
}

public void setModel_no(String model_no) {
this.model_no = model_no;
}

public SelectItem[] getNokia() {
return nokia;
}

public void setNokia(SelectItem[] nokia) {
this.nokia = nokia;
}

public SelectItem[] getSamsung() {
return samsung;
}

public void setSamsung(SelectItem[] samsung) {
this.samsung = samsung;
}

public SelectItem[] getModel() {
//
// this.model = nokia;
return model;
}

public void setModel(AjaxBehaviorEvent evt) {
if(company_name.equalsIgnoreCase(“nokia”))
this.model =nokia;
else if(company_name.equalsIgnoreCase(“samsung”))
this.model =samsung;
else if(company_name.equalsIgnoreCase(“sony ericson”))
this.model =sony;
else if(company_name.equalsIgnoreCase(“black berry”))
this.model =blackberry;
}

}

Advertisements

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.