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

jqform
|
+-- index.html
+-- WEB-INF
+-- web.xml
+-- classes
+-- simple.java
+-- simple.class

HTML Files

index.html

<html>
<head>
<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="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
// When the page is loaded, then..
// execute this function
$(document).ready(function(){
// When the button with id submit
// is clicked, this function should
// be executed
$("#submit").click(function(){
// 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
$("#displayMsg").load("/jqform/go?q="+val);
});
});
</script>
</head>
<body>
<input type="text" name="q" id="t"/>
<input type="button" id="submit" value="SUBMIT"/>
<div id="displayMsg"/>
</body>
</html>

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

web.xml

<web-app>
<servlet>
<servlet-name>puppy</servlet-name>
<servlet-class>simple</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>puppy</servlet-name>
<url-pattern>/go</url-pattern>
</servlet-mapping>
</web-app>

Servlet Programs

simple.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
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,