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

webapps
|
+- bs
|
+- index.html
+- WEB-INF
|
+- web.xml
+- classes
|
+- servlet.java
+- servlet.class

HTML File

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

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>
<servlet>
<servlet-name>myser</servlet-name>
<servlet-class>servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myser</servlet-name>
<url-pattern>/submit</url-pattern>
</servlet-mapping>
</web-app>


servlet.java - Program to write to a file

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
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");
fout.write(q.getBytes());
fout.close();
}
}

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,