Srikanth Technologies

Using JQuery with JSF

In this blog, I show how to use JQuery in JSF to make an AJAX request. Assume, we need to take username entered in inputText element of JSF form and check whether the username is unique in USERS table of Oracle database. For this we can use JQuery to make an AJAX request to checkuser.jsp, which checks for uniqueness of username and sends a message back to client. We then display the message sent from checkuser.jsp in a span item on the right of inputText component.

I assume you know how to use JQuery. In case if you are new to JQuery, please read my blog on how to use JQuery.

Follow the steps given below to integrate JSF with JQuery to make AJAX request.

Creating a new web project with JSF support

Take the following steps to create a new web application using NetBeans.

  1. Start NetBeans.
  2. Select File->New Project.
  3. Select Java Web in Categories and select Web Application in Projects.
  4. Enter JSFJQueryDemo as the name of the project and specify the folder where you want the project to be created.
  5. Select Apache Tomcat as the server. You can even select Glassfish.
  6. In Frameworks window, select JavaServer Faces as the framework.
  7. Click on Finish.

NetBeans creates a new web application with JSF 1.2 and JSTL libraries included. It also provides required JSF entries in web.xml (configuration of FacesServlet) and faces-config.xml .

Add OJDBC14.JAR, which contains Oracle Driver, to project using Libraries node in Project window.

Adding JQuery to project

Take the following steps to download and add JQuery library to your web application in NetBeans.

  1. Download JQuery from http://docs.jquery.com/Downloading_jQuery. The latest version as of now is 1.4.2.
  2. Place jquery-1.4.2.js file in Web Pages folder of your project and you are ready to use JQuery.

register.jsp

The following is register.jsp, which takes required information from user regarding registration. For this example, we focus only on validation of username and not the actual registration process.

The most important thing is to know how to access JSF component from JQuery. The id given to inputText is consisting of formid:componentid. So in this example the id given to textbox is  registerform:username. But the presence of : (colon) causes problem to JQuery. So, we need to escape : (colon) using two \\ characters before colon - registerform\\:username.


<%@page contentType="text/html" %>de">

<%@page contentType="text/html" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <script language="javascript" src="jquery-1.4.2.js"></script>
        <script language="javascript">
            function checkUsername(){
                $.get( "checkusername.jsp",{username : $("#registerform\\:username").val()},updateUsername);
            }
            function updateUsername(response)
            {
                if (response) {
                    $("#usernameresult").text(response);  // update SPAN item with result
            }
        </script>
        <title>Registration</title>
    </head>
    <body>
        <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
        <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
        <f:view>
           <h2>Registration </h2>
           <h:form  id="registerform">
           <table>
                    <tr>
                        <td>Username : </td>
                        <td><h:inputText id="username" value="#{userBean.username}"  required="true" onblur="checkUsername()" />
                            <h:message for="username" />
                            <span id="usernameresult" />
                    </tr>
                    <tr>
                        <td>Password : </td>
                        <td><h:inputSecret id="password" value="#{userBean.password}"  required="true" /> <h:message for="password" /> </td>
                    </tr>
                    <tr>
                        <td>Re-enter Password : </td>
                        <td><h:inputSecret id="confirmPwd" value="#{userBean.confirmPwd}"  required="true" /> <h:message for="confirmPwd" /> </td>
                    </tr>
                    <tr>
                        <td>Email Address  : </td>
                        <td><h:inputText id="email" value="#{userBean.email}" required="true" onblur="checkEmail()"  /> <h:message for="email" /> </td>
                            <span id="emailresult" />
                    </tr>
               </table>
                                
              <p/>
              <h:commandButton actionListener="#{userBean.register}" value="Register" />
              <p/>
              <h3><h:outputText value="#{userBean.message}" escape="false"  /> </h3>
              <p/>
           </h:form>
        </f:view>
    </body>
</html>lt;/f:view>
    </body>
</html>

The above JSF Form uses userBean, which is the name given to beans.UserBean class. The class and its entries in faces-config.xml file are given below.

beans.UserBean class

UserBean is the managed bean that stores data coming from JSF form. It contains an action listener - register(), which is supposed to process the data to complete registration process. We don't deal with it as our focus is only on validating username.

package beans;

public class UserBean {
    private String username, password, email,confirmPwd, message;

    public UserBean() {
    }

    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 getConfirmPwd() {
        return confirmPwd;
    }

    public void setConfirmPwd(String confirmPwd) {
        this.confirmPwd = confirmPwd;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void  register(ActionEvent evt) {
       if (! password.equals(confirmPwd))
       {
             message = "Passwords do not match!";
             return;
       }
       // do registration
    } // register
}

faces-config.xml

The following entry is required in faces-config.xml for UserBean managed bean.

    <managed-bean>
        <managed-bean-name>userBean</managed-bean-name>
        <managed-bean-class>beans.UserBean</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>

checkusername.jsp

Now create a checkusername.jsp to check whether given username is valid. It sends a message if username already exists otherwise it sends empty string (nothing).

<%@ page import="java.sql.*"  contentType="text/plain"%>
<%
 String username = request.getParameter("username");  // sent from client
 // connect to oracle using thin driver
 Class.forName("oracle.jdbc.driver.OracleDriver");
 Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","youruser","yourpassword");
 PreparedStatement ps = con.prepareStatement("select username from users where username = ?");
 ps.setString(1,username);
 ResultSet  rs = ps.executeQuery();
 if ( rs.next()) { // found username
    out.println("Username is already present!");  // send this to client
 }
 rs.close();
 ps.close();
 con.close();
%>
      

Deploy and Test

Now deploy the web application and run register.jsp. If you enter a username that is already present in USERS table then we get message - Username is already present - in SPAN item on the right of username field. If username is unique then SPAN item is set to empty string ( as JSP returns nothing).


Post Your Comment

Image

Enter the code given in the above image :
Enter Your Name :
Enter Your Email Address :
Enter Your Comment :

Comments


Posted By V On 12-Aug-10 11:13:10 PM

is there a way to call a managed bean method onblur, rather than coding the db access in a JSP ?



Posted By Kurt Pater On 22-Dec-10 10:57:29 PM

Nice article, helps a lot, thanks KP



Posted By srinivasu On 05-Jan-11 03:49:40 PM

Hi Vikrant for your question, you can move the scriptlet code to a bean class method or else you create a new DAO class where DB connection can be written over here and create an instance of DAO class in bean and perform a method call....



Posted By Yuri On 21-Feb-11 09:05:07 PM

Let me correct a code with DB connection. During query execution several exceptions may occur. So the code should be put in try/catch block:
<%@ page import="java.sql.*" contentType="text/plain"%>
<%
String username = request.getParameter("username"); // sent from client
// connect to oracle using thin driver
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{ DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","youruser","yourpassword");
ps = con.prepareStatement("select username from users where username = ?");
ps.setString(1,username);
ResultSet rs = ps.executeQuery();
if ( rs.next()) { // found username
out.println("Username is already present!"); // send this to client
}
} catch (Exception e){
if (rs != null){
rs.close();
}
// ... and so on
}
%>



Posted By himanshu goyal On 07-Dec-12 06:28:42 PM

hiii All
this is good example to understanading of basic jaf