Sunday, April 24, 2011

JQuery Servlet Ajax application

In this post, I am demonstrating a simple ajax application using jquery and java servlets.


My other JQuery posts will be listed here.

In this Sample Project, I am trying to suggest the names of the countries starting with A.

So, if we type more than two letters, than it suggests the names of the countries.

The following is the screenshot for the above application.



First we define a html file as follows:

<%@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>JQuery Example</title>
    </head>
    <body>
        <center>
            <h3>Ajax Example using JQuery and Servlets</h3>
        </center>
        <script type="text/javascript" src="jquery-1.5.1.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                alert("Thanks for visiting!");
                $(".name").keyup(function(){
                    $country = $("#name").val();
                    if ($country.length > 1) {
                        $.ajax({
                            url: 'SampleServlet',
                            type: "POST",
                            data: {country:$country },
                            error: function(){
                                alert("Data Error");
                            },
                            success: function (data){
                                $("#flag").html("Country Suggestion: " + data) ;
                            }
                        });
                    }
                });
            });
        </script>
        <form id="sampleform" >
            <center>
                Enter Country starting with A:  
                <input id="name" class="name" type="text" >                                                    
                 <br/><br/>
                <div id="flag"> </div>
                <br/><br/><br/>
                Type Atleast Two Letters *
            </center>
        </form>
    </body>
</html>



The above program needs "jquery-1.5.1.js" file which is a JQuery library.

Save this file as .js file. This library should be placed in the same location where the jsp page is present.

This jsp program is calling SampleServlet Program as follows:

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


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Sriram
 */
public class SampleServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet SampleServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet SampleServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
            */
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the
            + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String name = request.getParameter("country") ;
        System.out.println(name);
        String result = this.countryList(name) ;
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println(result);
    }

    public String countryList(String name) {
        String country[] = new String[5] ;
        country[0] = "America" ;
        country[1] = "Australia" ;
        country[2] = "Argentina" ;
        country[3] = "Africa" ;
        country[4] = "Antartica" ;

        int flag = name.length() ;
        for (int i = 0 ; i < country.length ; i++) {
            if (country[i].substring(0, flag).equalsIgnoreCase(name)) {
                return country[i] ;
            }
        }
        return "Country Not Available in List!!" ;
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


The web.xml configuration for the SampleServlet program is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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-app_2_5.xsd">
    <servlet>
        <servlet-name>SampleServlet</servlet-name>
        <servlet-class>SampleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SampleServlet</servlet-name>
        <url-pattern>/SampleServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>


The jsp program atleast two let as parameter and sends it to POST method in SimpleServlet using ajax. There is a callback function which displays the output in an alert box and ultimatly in the jsp page.


There Source code is given as follows. It consists of a war file. Place this war file in the webapps folder of your server and paste http://localhost:8080/Sample/Sample.jsp in the url of the browser.

No comments:

Post a Comment