Saturday, April 23, 2011

Simple JQuery-Servlet Application

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

Name the project as Sample.The jsp program here calls the GET method.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JQuery Example</title>
            <h3>Getter Example using Servlets</h3>
        <script type="text/javascript" src="jquery-1.5.1.js"></script>
        <script type="text/javascript">
                alert("Thanks for visiting!");
                    alert($name) ;
                    $.get("SampleServlet", {name:$name}, function(data) {
                        alert(data) ;
                        $("#flag").html(data) ;
        <form id="sampleform" method="POST">
                Enter your Name:  <input id="name" class="name" type="text">  <br/><br/>
                <input class="Submit" name="Submit" type="button" value="Submit" id="Submit"> 
        <div id="flag"> </div>

** 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:

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 {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String name = request.getParameter("name") ;
        PrintWriter out = response.getWriter();
        out.println("Hello " + name);

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);

     * Returns a short description of the servlet.
     * @return a String containing servlet description
    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="" xmlns:xsi="" xsi:schemaLocation="">
The jsp program takes a name as parameter and sends it to GET 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.

Download Source Code

No comments:

Post a Comment