Learn Servlets in an Easy and Fast way

servlets in Java

Introduction to Servlets

Servlets are very important milestone while building an application in J2EE. In this post, we will discuss more details about Servlet life cycle, How to write Servlet class, the difference between CGI and Servet in details.

What is the difference between Servlet and CGI?

Most of the time rather almost every alternate year this question is going to rock the engineering students who are in Information Technology or Computer science background. I am writing this post for the students who need a quick answer on this.

Ads code goes here

What is the difference between Servlet and CGI?

CGIServlet
CGI is very initial attempt to work with a client-server architecture. A CGI creates a new process every-time it receives a new request from the client. This can be written in various language. A heavyweight processServlet is more advanced for client-server architecture As it is proved by java, it processes a new thread upon getting new request. It is a lightweight process
Number of the process for any server is  predefined, hence multiple requests if, went to the server and server could not process it, there may be a loss in the process via requestThread is a lightweight process it is true but there is no limit for that, hence there is no loss in the process.
CGI executes the processes in their own OS Shell, doesn’t have concurrency conflicts. but the creation of OS shell is a heavyweight process. It takes a higher time to be created. The process life cycle takes a lot of time to complete and it affects response time of the server (goes high.)The first time a Servlet is requested, it is loaded into memory and cached. From then on, the same Servlet instance is used, with different requests being handled by different threads. Thread lifecycle is very short hence improve the server response.
CGI is mainly for text processing application where less or no security or object orientation process required.Servlet is for Enterprise application where mostly we use object orientation
CGI servers require to start a new interpreter for every request which eats up the resources and probable processUpon request, a new thread is opened so no need to open interpreter.
There might be a chance Client submits a request to CGI that terminates before responding. The browser will be still in waiting for information mode.Not possible in Servlet
Any bug can not crash the webserverAny bug can is easily caught by the exception handler.
CGI is not scalable moreover programming language is platform dependent. If you change the operating system, the CGI process may fail. we need to recompile everything for the new OS.Powered by Java. Hence highly scalable and servlet programming is platform-independent as long as the JVM is running and supported by OS.
No separation between presentation and business layer.CGI cannot read and set HTTP headers, handle cookies, tracking sessions.Business layer and Presentation layer is always different as Servlet can read and set HTTP headers, handle cookies, tracking sessions.
CGI can process only one requestServlet can process multiple requests.
CGI is not based on pooling (which hold no external resource but occupy memory i.e. not destroy after used) Its container-managed pooling object.JVM supports pooling of objects so as Servlet.
CGI creates its own memory space for every request viz process.Servlet shares the memory space.
Advantage of CGI is that it can process and run any script any given point of time.In servlet, any script first gets translated into java then it gets compiled and runs.
READ  How to Resolve NoSuchSessionException in selenium free?

Why Client Side Applet is over??

  • What happens, when we try to access a page which is having applet embedded in it, the byte code of the applet starts to download to the client machine. if your applet is small enough then it is beautiful but if it is huge?? yes, the downloading time becomes a headache for new techies.
  • Apart from this, there is also a compatibility problem. To run an applet your browser has to have the applet compatible. Think about today’s scenario, The client-side means a laptop, a desktop, a server, a tablet even the new smartphones have the browser facility. All they may not have browser compatibility.
  • The third is the security issue with the local applet. The applet, when talking to the database, may give more access to secure data to the user if not coded properly. The client-side applet can open a connection to the server which stays behind the firewall. Now getting a response from the server through RMI is a real pain.

For these reasons the applet -client side is not a good practice while coding. Rather there are several javascript available which will give more great GUI feature.

The applet is termed as it runs in the client-side. But servlet is termed as that java code(applet) runs on the server-side. Ser-let.!!!

What is Servlet life Cycle?


Mostly a Servlet is having 3 major stages.

  1. Initialization—-init() method
  2. Service——–service()method
  3. Destruction—-Destroy() method

If you are trying to create a servlet program of your own, the two main class for servlet implementation are-

  1. GenericServlet—For all general purpose servlet capable of handling any protocol.
  2. HttpServlet— HttpServlet is a extended class from GenericServlet , handles only HTTP protocol.

So when we try to create any of the servlets of our own, we need to extend one of these classes.
P.S-Servlet does not contain any main() method instead it is having a service() method to work.

if you are extending GenericServlet:
public abstract void service(ServletRequest req,ServletResponse res) throws ServletException,IOException;

The two types of object a service method accepts are

  1. Request–the information directing to the servlet
  2. Response–The information towards server viz client

if you are extending  HttpServlet :
well, this is a bit advanced process. whenever you are extending to HttpServlet, the service() method is written there.so we need to invoke that method. HttpServlet.service().
protected void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
The best part of this when the service method is called, it determines the request and which methods to be called. Say we have the method type is GET then doGet() method is called or else if we have posted as request method then corresponding doPost() method is called.
Note: All these methods can be overridden.
The other methods inside a HttpServlet’s service method are-

  1. doDelete()
  2. doGet()
  3. doOption()
  4. doPost()
  5. doPut()
  6. doTrace()

Image source:http://book.javanb.com

Init method:

Init() is the method when a servlet starts and a servlet’s life cycle begins. It is called when server instantiated the servlet. The major advantage is, it is called only once in its life cycle. Init method creates or initializes all the required resources that will be used during it’s lifetime.
The Signature is —


public void init(ServletConfig config) throws ServletException
it takes the ServletConfig object as a parameter and pass it to the super init method.
super.init(config);
So the structure of a init method looks like---
            public void init(ServletConfig config) throws ServletException {
super.init(config);
}

The important aspect of this signature is that a init method can throw an exception ServletException.When it occurs??? If the init method could not initialize all the required resources that will be used during its lifetime.

Service method:

As the picture depicts, once the init method is called, the second step is to call the Service method. So Service method can not be called if the init method is not called. This method talks to client .. I mean this method takes care of the request and response. We generally do not implement this method but if our servlet class is extended to GenericServlet then we need to implement that. Service method supports HTTP /1.1 and above.
The method looks like-


protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

 

READ  Abstract Class Format in Java

Destroy method:

This method is the end of servlet’s life cycle. if we shut down a service, this method is automatically called. All the resources that were consumed by the init method are released. This is kind of garbage collection of core java. Also, some important aspect like closing database connection, closing file system or any important information if required for the next run.
The method looks like–


 public void destroy()

 

How to call multiple Servlets from a single Servlet?

To call multiple servlets from a single servlet is taken from StackOverflow.


public class Populate_ALL extends HttpServlet {
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
   response.setContentType("text/plain");
   request.getRequestDispatcher("/Servlet2").include(request, response);
   request.getRequestDispatcher("/Servlet3").include(request, response);
   request.getRequestDispatcher("/Servlet4").include(request, response);     
   //...
    }
   }

Difference between include and forward method with code

definition forward()

this method is used to forward a request to another servlet (or JSP). So no response from parent to child is propagated. Also from the point, the forward method is called, control goes to call or the child servlet.

Servlet-4 coding-forward()

Raw code


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;

public class Servlet4 extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

public void init(ServletConfig config) throws ServletException {
super.init(config);
}

public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet4</title></head>");
out.println("<body>");

String text1=request.getParameter("text1");
String msg ="<p>The servlet has received a GET. Servle4.This is the reply.</p>";
RequestDispatcher rd = request.getRequestDispatcher("/servlet5");
request.setAttribute("text1",text1);
out.println("came back to servlet 4");
out.println(msg);
if (rd != null)
//  rd.include(request, response);
rd.forward(request, response);

out.println("</body></html>");
out.close();
}

public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet4</title></head>");
out.println("<body>");
out.println("<p>The servlet has received a POST. This is the reply.</p>");
out.println("</body></html>");
out.close();
}
if you want to implement service method instead of doGet() and doPost()
/*  public void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet5</title></head>");
out.println("<body>");
String text1=request.getParameter("text1");
String msg ="<p>The servlet has received a GET. Servle4.This is the reply.</p>";
RequestDispatcher rd = request.getRequestDispatcher("/servlet5");
request.setAttribute("text1",text1);
out.println(msg);
if (rd != null)
//    rd.include(request, response);
rd.forward(request, response);
out.println("came back to servlet 4");
out.println(msg);
out.println("</body></html>");
out.close();
}*/
}

 

The output will be

definition include()

this method is used to call the new servlet or process the request to another servlet (or JSP) with some data passing through the parent to child or calling servlet to called servlet.response from parent to child is propagated. Also from the point, the include method is called, control goes to called or the child servlet and comes back.
All the out. println command before the include method is called is propagated to child servlet as part of the response.

Servlet-4 coding-include()

Raw code:

Same as above but the  open include instead of forwarding


          rd.include(request, response);
        //rd.forward(request, response);

The output will be

How to Call a servlet from HTML using Ajax

Following this link this can be done in the following manner:
your HTML will look like-


<head>
<title>Checking login in AJAX</title>
<script type=”text/javascript”>
 function getXMLObject()  //XML OBJECT
{
 //Not changing his original values
var xmlHttp = false;
   try {
     xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”)  // For Old Microsoft Browsers
        }
        catch (e) {
    try {
       xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”)  // For Microsoft IE 6.0+
        }
        catch (e2) {
       xmlHttp = false   // No Browser accepts the XMLHTTP Object then false
       }
       }
   if (!xmlHttp && typeof XMLHttpRequest != ‘undefined’) {
     xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
      }
   return xmlHttp;  // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object

function ajaxFunction() {
  //get the values from textboxes
  var userIn=document.myForm.id.value;
  var pwd=document.myForm.pwd.value;
  alert(userIn);
  if(xmlhttp) {
    xmlhttp.open(“POST”,”servlet1″,true); //gettime will be the servlet name
    xmlhttp.onreadystatechange  = handleServerResponse;
    xmlhttp.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’);
    //send them to server one by one .You can send more data one by one..I customized this part
  xmlhttp.send(“id=” + userIn);
    xmlhttp.send(“pwd=” + pwd);
  }
}

function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
   
     if(xmlhttp.status == 200) {
 
       //document.myForm.time.value=xmlhttp.responseText; //Update the HTML Form element
       document.getElementById(“text”).innerHTML=xmlhttp.responseText;
     }
     else {
        alert(“Error during AJAX call. Please try again”);
     }
   }
}
</script>
        <body>
        <form name=”myForm” method=”POST” action=”Servlet1″>
        Enter your ID<input type=”text” name=”id” />
        <br />
        Enter your Password<input type=”text” name=”pwd” />
        <input type=”button” onClick=”javascript:ajaxFunction();” value=”Click to check teh userName”/>
        <br />
        <div id=”text” name=”validation” />
        </form>
        </body>
        </head>
        </html>

Server-side servlet will be something


import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servlet1 extends HttpServlet {
    private static final String CONTENT_TYPE = “text/html; charset=windows-1252”;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }
public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {
     
        doPost(request,response);
 
    }

    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
                    PrintWriter out = response.getWriter();
                String name = null;
                String pwd=null;
                if(request.getParameter(“id”) != null) {
                                        name = request.getParameter(“id”);
                                     
                                }
                                else {
                                       name = “”;
                                }
               //put your logic here
                if (name.equals(“Animesh”))
                {
                       //based on the logic send response back
                                out.println(“You have successfully logged in:” + name);
                }
                else
                out.println(“This is not a valid login” + name);
               }
}

How to get multiple form data in servlet?

Sample HTML will have lot more textboxes…


<input type="text" name="text1" value="text" maxlength="20" size="20"/>
            <br/>
            <input type="text" name="text2" value="text" maxlength="20" size="20"/>
            <br/>
            <input type="text" name="text3" value="text" maxlength="20" size="20"/>
            <br/>
            <input type="text" name="text4" value="text" maxlength="20" size="20"/>
            <br/>
            <input type="submit" name="Submit" value="Submit"/>

The html overall looks like—

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"></meta>
    </head>
    <body>
        <form action="servlet2" method="get" enctype="text/plain" name="sample">
            <input type="text" name="text1" value="text" maxlength="20" size="20"/>
            <br/>
            <input type="text" name="text2" value="text" maxlength="20" size="20"/>
            <br/>
            <input type="text" name="text3" value="text" maxlength="20" size="20"/>
            <br/>
            <input type="text" name="text4" value="text" maxlength="20" size="20"/>
            <br/>
            <input type="submit" name="Submit" value="Submit"/>
        </form>
     
    </body>
</html>

Here four text boxes are trying to send data to the server…The Name of the servlet which is trying to catch those data is “servlet2”

READ  How to write a servlet chain

In servlet, there are three ways how you can catch those data…

  • public Enumeration ServletRequest.getParametersName()…will give you the parameters names…for this example-text1,text2,text3,text4..so you will get the list and need to iterate by calling another method getParameter();
  • public String ServletRequest.getParameter(String name)—When you know the exact name of field name and want to get the corresponding value. This will return an only String value.
output---Client end
output—Client end

Let’s check the first function–

  String temp=null;
        Enumeration param=request.getParameterNames();
        while(param.hasMoreElements()) {
            temp=(String)param.nextElement();
            out.println(temp);
             
        }
        value=request.getParameterValues("text1");
        out.println(value[0]);

For the second function…


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        String data=request.getParameter("text");
        PrintWriter out = response.getWriter();
        out.println("");
        out.println("");
        out.println("");
     
        out.println("Your data is "+data+"--->"+request.getParameter("text1"));
out.println("Your data is "+data+"--->"+request.getParameter("text2"));
out.println(" Your data is "+data+"--->"+request.getParameter("text3"));
out.println(" Your data is "+data+"--->"+request.getParameter("text4"));
out.println("
");
        out.close();
    }

When you are getting more than one value through a single variable

 

Well, this might occur in very rare…but yes Servlet also have a answered this situation. say all of your field names are text or you are appending all the values to a single variable and sending it to server viz servlet. So there has to have a mechanism to read that value as well…

String[] value;
        value=request.getParameterValues("text1");
        out.println(value[0]);

or else you can find out the size of the array and loop through for the values.
so how the servlet will look like–

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.*;
import javax.servlet.http.*;

public class Servlet2 extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    /**Process the HTTP doGet request.
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        String data=request.getParameter("text");
        PrintWriter out = response.getWriter();
        out.println("");
        out.println("");
        out.println("");
     
        out.println("The servlet has received a GET. This is the reply.Your data is"+data+"--->"+request.getParameter("text1"));
out.println("The servlet has received a GET. This is the reply.Your data is"+data+"--->"+request.getParameter("text2"));
out.println("The servlet has received a GET. This is the reply.Your data is"+data+"--->"+request.getParameter("text3"));
out.println("The servlet has received a GET. This is the reply.Your data is"+data+"--->"+request.getParameter("text4"));

//method two
String temp=null;
String[] value;
Enumeration param=request.getParameterNames();
while(param.hasMoreElements()) {
temp=(String)param.nextElement();
out.println(temp);

}
value=request.getParameterValues("text1");
out.println(value[0]);
out.println("");
        out.close();
    }
 }

Share and Enjoy !

1 thought on “Learn Servlets in an Easy and Fast way”

  1. Have you ever considered about including a little bit more than just your articles?
    I mean, what you say is important and all. But imagine if you added some great images or video clips to give your posts more,
    “pop”! Your content is excellent but with pics and videos, this site could certainly be one of the most beneficial in its niche.
    Very good blog!

Leave a Comment

Your email address will not be published. Required fields are marked *