Servlet Tutorial

A Servlet is a class that extend the capabilities of servers and it can respond to any type of incoming requests.The Servlet API is a Java EE API which contains the interfaces and classes for creating Servlet components.A Java Servlet is an object which runs in a Servlet Container.The Servlet Conatiner runs in a Web server (like Tomcat) . A  container can manage any number of Servlets in it.

Servlet Lifecycle

The life cycle is managed by the container. The steps in the Servlet life cycle are :

  • Loads the Servlet
  • Creates the instance
  • Calls the init() method
  • Calls the service() method
  • Calls the destroy() method

When a request is mapped to a particular servlet , then the container performs the following things.

1)If the servlet is calling for the first time ,the container is loading the servlet and creates an instance.Then calls the init() method.

2)Invokes the service() method .

3)If the servlet object needs to be removed , then the destry() method of servlet would be invoked by the container and  the servlet would be finalized.

Creating a Servlet class

The base interface for creating servlet is the Servlet interface.The easiest way to create a servlet is either 1)By creating a sub class of  GenericServlet class , or 2)by  sub classing the HttpServlet class.

GenericServlet vs HttpServlet 

GenericServlet directly  implements  the Servlet interface.A sub class of GenericServlet should override the  service() method. The service() method  accepts a simple ServletRequest object as request object and gives ServletResponse  object as response.

But HttpServlet is not a direct implementation of Servlet interface.Instead it is a sub class of GenericServlet.Also it is an abstract class . A sub class of HttpServlet accepts only HttpRequest and gives only HttpResponse.In other words , it supports only Http Protocol.

The HTTP service methods are :

doGet() – For supporting HTTP GET requests
doPost() – For supporting HTTP POST requests
doPut() For supporting HTTP PUT requests
doDelete() – For HTTP DELETE requests
doTrace() – For HTTP TRACE requests
doHead() – For HTTP HEAD equests.A HEAD request is for getting the headers of a response
doOptions()For HTTP OPTIONS request.An OPTIONS request is sent from the client when it needs to know the available HTTP methods

A sub class of HttpServlet should override at least one of the above.The first four are the important ones.Others are less significant

Also there are few important methods too.They are:

init() and destroy() – To manage resources that are held for the life of the servlet

getServletInfo() – Used by the servlet to give the information about itself

Servlet example

Now let us see a Servlet example.We are going to create a servlet in Apache Tomcat server and trying to invoke the same Servlet from a jsp page.

Tools & Software needede

1)Eclipse

2)Apache Tomcat

3)Java EE sdk pre installed  environment

Steps

1)Open eclipse in a suitable work space

2)Create a dynamic web project.In this case ,let it be ServletSample

servlet_Create_Project

3)Press Next and then Finish.Select the Generate Deployment Descriptor check box before pressing the Finish

4)Now expand the project and right click on the src and create a package with suitable name.Let it be com.servlet.samples

servet_Create_package

5)Now right click on the newly created package and create a new Servlet.Give s suitable name .Let it be SampleServlet

servlet_Created

6)If the generated class is having compilation issues , then download the javax- Servlet jar file  from here.We used version 3.0 in this example.Extract the zip file and copy the jar file to WebContent/WEB-INF/lib of the created project.Now clean the project

7)Now edit the web.xml deployment descriptor as shown here.



  ServletSample
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
  sampleServlet
  com.servlet.samples.SampleServlet
   
  
  sampleServlet
  /sampleServlet
  

8)Now create two jsp files in /WebContent directory. First jsp page needs to give a  user entered  string input to the servlet.Then the servlet calls the second jsp page to display the  entered string.Let the files names be inputPage.jsp and outputpage.jsp

inputPage.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>




Please enter your input 


Enter your input

9)Now change the doPost() method of  the servlet class.So the SampleServlet.java becomes:

SampleServlet.java

package com.servlet.samples;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class SampleServlet
*/
@WebServlet("/SampleServlet")
public class SampleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public SampleServlet() {

}


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

}

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

String inputString = request.getParameter("inputString");
System.out.println("The String entered by user is " + inputString);
String redirectUrl = "outputPage.jsp?outputString="+inputString;
response.sendRedirect(redirectUrl);


}

}

 

10)Now create a new Apache Tomcat server and add the  project  to server.We user Tomcat 7.0.

Servlet_server_add

11)Publish and restart the server.

12)Once the server started , right click on the inputPage.jsp and run it on server.

enterInput_1

13)When the text area appears , enter any string and press  submit.Now the output page would be showing the text we entered

outputSee Related Discussions

Java Mail Tutorial

EJB Tutorial

JPA Tutorial

JMS Tutorial

Web service Tutorial

JNDI Tutorial