Spread the love

Learn Servlet in an Easy and Fast way

Spread the love

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.

What is the difference between Servlet and CGI ?

CGIServlet
CGI is very initial attempt to work with client server architecture.A CGI creates a new process every-time it receives a new request from client.This can be written in various language.Basically a heavy weight processServlet is more advanced for client server architecture As it is proved by java,it process a new thread upon getting new request. It is lightweight process
Number of process for any server is  predefined,hence multiple request if , went to the server and server could not process it , there may be a loss in process via requestThread is a light weight process  it is true but there is no limit for that,hence there is no loss in process.
CGI executes the processes in their own OS Shell, doesn’t have concurrency conflicts. but creation of OS shell is a heavy weight process.It takes a higher time to be created. Process life cycle takes a lot of time to complete and it effects 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 requires 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 web serverAny bug can is easily caught by exception handler.
CGI is not scalable moreover programming language is platform dependent.If you change 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 request.
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 precess and run any script any given point of time.In servlet any script first get translated into java then it gets compiled and run.

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 smart phones have the browser facility. All they may not have browser compatibility.
  • Third is the security issue with local applet.The applet , when talking to 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 firewall.Now getting response from server through RMI is a real pain.
READ  Friends
READ  Friends

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.

Applet is termed as it runs in client side.But servlet is termed as that java code(applet) runs on 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 servlet 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 bit advanced process. when ever 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 post 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 create or initializes all the required resources that will will be used during it’s life time.
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 occures??? If the init method could not initializes all the required resources that will will be used during it’s life time.

Service method:

As picture depicts, once the init method is called , the second step is to call Service method. So Service method can not be called if the init method is not called. This methods actually talk 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 support HTTP /1.1 and above.
The method looks like-


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

 

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 init method is 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 next run.
The method looks like–


 public void destroy()

 

READ  How to write a servlet chain

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 called 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();
}*/
}

 

READ  Best places to visit in Neil Island

The output will be

definition include()

this method is used to call the new servlet or process the  a 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 response.

Servlet-4 coding-include()

Raw code:

Same as above but the  open include instead of forward


          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 there are four text boxes trying to send data to the server…The Name of servlet which is trying to catch those data is “servlet2”

READ  Documentation Accessibility for Oracle Test suite
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 fieldname and want to get the corresponding value. This will return only String value.
output---Client end
output—Client end

Lets 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();
    }
 }

 




Spread the love
Animesh Chatterjeehttps://techtravelhub.com/
I am the founder and owner of the blog - TechTravelHub.com, always love to share knowledge on test automation,tools,techniques and tips.I am a passionate coder of Java and VBScript.I also publish articles on Travel ideas and great honeymoon destinations.Apart from these, I am a gear-head,love to drive across India. I have shared lots of articles here on How to travel several parts of India.Customization of cars aka car modification is my another hobby.Get in touch with me on ani01104@gamil.com

Related Articles

A Little France in India Pondicherry Travel Plan

This is my experience and handpicked travel spots to make a...

Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Recent Posts

Learn Quickly About DevOps Tools in a Fast and Efficient Manner

Introduction to DevOps tools DevOps tools are a collection of...

How to Collaborate between Development and Operations Team Fast and Effectively

Collaborate between Development and Operations Teams are the key...

Learn How to Use Jacoco Java code Coverage

Introduction to Jacoco Jacoco provides a wide range of coverage(analysis...

EDITOR PICKS


Spread the love