In this article, I am going explain about Servlets in Java briefly then i am going to give you simple example of how we can save data in the database using HTML form fields values using Servlets in J2EE.

So before we begin to save values, first let me give a brief introduction about servlets.

Servlets in Java

Servlet technology is used to create a web application (resides at server side and generates dynamic web page). Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface.There are many interfaces and classes in the servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse etc. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests.

So, Servlet is a class that extends the capabilities of the servers and responds to the incoming request. It can respond to any type of requests & it is a web component that is deployed on the server to create the dynamic web page.

HttpServlet class

The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides HTTP specific methods such as doGet, doPost, doHead, doTrace etc.Read more about its Methods

Example Servlet:

import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet {

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		out.println("<h1>Hello world!</h1>");
		out.println("<p>This is our first servlet.</p>");
	}
}

In the above code, you can see, it overrides the doGet() function, which takes a HttpServletRequest and a HttpServletResponse as parameters. Inside the doGet() function, we get a PrintWriter from the response and we output some HTML content to it.

Save this to a file named HelloWorldServlet.java. You can put this file anywhere you want.

Just like any other Java file, we have to compile this into a .class file. The only trick is that we need to make sure the Java servlet API is on our classpath.

The Java servlet API is a library that comes with Jetty (or with any other server). It’s located in the lib folder inside our Jetty directory. For example, mine is located at C:/Users/jai/Desktop/jetty/lib/servlet-api-3.1.jar. So to compile my HelloWorldServlet class, I would add that .jar file to my classpath using the -cp argument, like this:

javac -cp C:/Users/jai/Desktop/jetty/lib/servlet-api-3.1.jar HelloWorldServlet.java

This should create a HelloWorldServlet.class file.

The web.xml File

Even though HelloWorldServlet is a normal Java class, it doesn’t have a main() function, so how do we run it? The answer is we don’t! Instead, we need to tell our server to run it for us when a user requests a certain URL from it. To do that, save this XML into a file named web.xml:

<web-app>

	<servlet>
		<servlet-name>MyHelloWorldServlet</servlet-name>
		<servlet-class>HelloWorldServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>MyHelloWorldServlet</servlet-name>
		<url-pattern>/index.html</url-pattern>
	</servlet-mapping>

</web-app>

let’s take  a look on the above created web.xml file code details,step by step:

  • The outermost <web-app> tag means that we’re defining properties to set up a web app on our server.
  • The <servlet> tag tells our server about the servlet class we just wrote.
    • The <servlet-name> tag gives our servlet a name. This can be anything you want. It’s only used inside this web.xml file and isn’t visible to users!
    • The <servlet-class> tag specifies which class should be used for this servlet. Note: if your class is in a package, include that in the tag!
  • The <servlet-mapping> tag tells our server which URLs should trigger which servlet classes.
    • The <servlet-name> tag references the name we defined in the <servlet> tag. Make sure it matches.
    • The <url-pattern> tag tells the server which URL should trigger our servlet. Note that this is relative to our web app (more on that in a second).

So, this web.xml file tells our server that when a user requests the index.html URL, it should trigger our HelloWorldServlet class.

Example to get data from form using Servlet

First, we need to create an HTML form with two fields Email & password, with a button, after clicking that button we will send the form to the servlet, with the of which we will save values in the database.

So for that, we have to create a Servlet. Inside service() method we can insert the data in the Database only and only if there is a connectivity between our Database and the Servlet. To establish the connection between our Database and the Servlet we firstly need to call the method forName() which is static in nature of the class Class. It takes one argument which tells about the Database driver, which we are using. Now use the static method i of the DriverManager class. This method takes three arguments and returns the Connection object. SQL statements are executed and results are returned within the context of a connection. Now Database connection has been established.

Now use the method prepareStatement() of the Connection object which will return the PreparedStatement object and takes one a query which we want to fire as its input. The values which we have got from the HTML will be set in the Database by using the setString() method of the PreparedStatement object.

The code for the above HTML form would be

<html>
<head> <title>Login</title> </head>
<body>
<form method="POST" action="/InsertData">
  <p>Enter Name :
 <input type="text"  name="username" size="20"></p>
  <p>Enter Password : 
 <input type="password" name="password" size="20"></p>
  <input type="submit" value="Submit" name="SubmitButton"></p>
</form>  
</body> 
</html>

in the above form, we have defined a method as "post" and action as "InsertData"

Servlet Code of InsertData can be as the following

import java.io.*;
import java.lang.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class InsertingData extends HttpServlet{
  public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
        try{
      //get Username
      String username = request.getParameter("username");

     //get password
      String password = request.getParameter("password");
      out.println(username);
      out.println(password);

      //Get Connection Driver to establish database connection
      Class.forName("oracle.jdbc.driver.OracleDriver");
  //Establish connection
Connection con=DriverManager.getConection("jdbc:oracle:thin:@localhost:1521:xe","jaiprakash","admin123");

      //Write SQL query to insert data
      PreparedStatement pst = con.prepareStatement("insert into emp_info values(?,?)");
      pst.setString(1,username);
      pst.setString(2,password);
      int i = pst.executeUpdate();
      //Check if values are saved successfully or not
      if(i!=0){
        out.println("<br>Record has been inserted");
      }
      else{
        out.println("failed to insert the data");
      }
    }
    catch (Exception e){
      out.println(e);
    }
  }
}

If you will check above code, I have commented out important lines to make its meaning and uses clear.