Background Form Submission in Servlets

Here is how to submit a HTML form in background without leaving the page. This is a simple example that doesn't make use of the AJAX. I could rather say it as a simple HTML technique.

This is in fact a long lasting dream of mine. While I am satisfied, I ain't completely satisfied. However, this WILL help you if you don't want to submit the form normally or in background with AJAX.

In this example, I've put a simple <iframe> which isn't displayed. When the user clicks on the button, the thing is done in background. But the problem here, is that we don't know the response from the server. We just need to hope that the things are done fine.

I would STRONGLY recommend using AJAX if you would like to know the response from the server. This is the best way. The entire page here is being loaded, but the only thing is that it isn't visible to the user thereby giving him a feel that the form is submitted in the background.

Folder structure

+- bs
+- index.html
+- web.xml
+- classes
+- servlet.class


<title>Background Form Submit</title>
<form action="/bs/submit" method="post" target="m">
<input type="text" name="q" size="40"/>
<input type="submit" value="SUBMIT"/>
<iframe name="m" style="display:none"/>

Here as the target of the submit page is iframe which is not displayed, there is nothing the user can see that a new page is loaded.

web.xml - Deployment descriptor

</web-app> - Program to write to a file

import javax.servlet.*;
import javax.servlet.http.*;
public class servlet extends HttpServlet
public void doPost(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
String q=req.getParameter("q");

// I am writing it to a file
FileOutputStream fout=new FileOutputStream("out.txt");

Note: The file out.txt is written in the Tomcat folder (ex. Tomcat7.0) but not in the project directory. In the next example i'll be telling how to submit form in background using AJAX, so that you get the response from the server too.

Posted by at on

Tags: Servlets, Tricks Bag,