Submit a Form to Servlet using JQuery

Here is how to submit a form in background to servlet using JQuery in one single line. The scope of the program is to print a hello message in a html div. Note that you need to have a basic knowledge of JQuery and Javascript to understand this. But I'm pretty sure that the helpful commentaries will give you an understanding even if it is your first sight :)

Folder structure

C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\jqform

Project structure

+-- index.html
+-- web.xml
+-- classes
+-- simple.class

HTML Files


<title>JQuery - Servlet form submission</title>
<!--To use jquery, loading this is mandatory-->
<!--If you don't have internet connection, download this file
and give the local path
<script src=""></script>
// When the page is loaded, then..
// execute this function
// When the button with id submit
// is clicked, this function should
// be executed
// Get the value in the val field
var val=document.getElementById("t").value;
// Now, get the element with id displayMsg
// and in it load the given file
// The text printed in the servlet class now
// comes in the displayMsg div
<input type="text" name="q" id="t"/>
<input type="button" id="submit" value="SUBMIT"/>
<div id="displayMsg"/>

Here, the load() method takes a string which corresponds to the page that is to be loaded. Here, we are indirectly calling the page http://localhost:8080/jqform/go?q=gowtham (when you type 'gowtham' in the input field) and that the content in the page is pasted in the displayMsg division. In other words, simply, the above page is loaded in the div instead of a new page. That's it.

Deployment Descriptor



Servlet Programs

import javax.servlet.*;
import javax.servlet.http.*;
public class simple extends HttpServlet
public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
String q=req.getParameter("q");
// Get write object and print
PrintWriter pw=res.getWriter();
pw.println("Hello "+q);

Posted by at on

Tags: JQuery, Servlets,