Wednesday, March 11, 2020

Creating First Servlet

Creating First Servlet

Servlets are Java programs embedded with HTML Markup and enhance the capabilities of the Server. Servlets are server-side components of a request-response architecture and have their life-cycle managed by the servlet container. Java servlets are part of J2EE specifications and contained within the javax.servlet and java.servlet.http packages.

The Servlets are run inside the Java Enabled web server, generally known as the application server. This server has all the specifications and environment required to execute the Servlets.  

Apache Tomcat

Apache Tomcat (also referred to as Tomcat Server) implements several Java EE specifications including Java Servlet, JavaServer Pages (JSP), Java EL, and WebSocket, and provides a "pure Java" HTTP web server environment in which Java code can run.
Basically, there are three components of Tomcat
  • Catalina (a servlet container)
  • Coyote (an HTTP connector)
  • Jasper (a JSP engine)
Apache is the webserver, to receive and respond with HTTP request and response.

Tomcat Apache


Apache JServ Protocol (AJP) is a binary protocol that can proxy inbound requests from a web server through to an application server that sits behind the webserver.


Step 1:

First download and Apache Tomcat, you can download the zip file from this link, Unzip this file to extract the Apache Tomcat. 

Step 2: 

Go to Eclipse, file->new->dynamic web project. (First, make sure that correct perspective is chosen, Go to window->open perspective->J2EE perspective)

dynamic web project


Step 3:

Fill the Appeared window with the project name, add runtime(Add downloaded Apache Tomcat to the runtime) and select the web module version,

Dynamic web module
Dynamic Web Module 

Step 4:

Click "Next" and move ahead,

Step 5:

Click the checkbox for the deployment descriptor and click finish.

deployment descriptor


Step 6:

Right-click on your project name in the project explorer, file->new->servlet as give below,

create servlet

Step 7:

Provide the Servlet with some name and click "Next", Keep clicking next until this window,


Step 8:

You will get Servlet class template,


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;

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
      
    public MyServlet() {
        super();
    }

      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // WRITE YOUR CODE HERE
            //.....................
      }
}


The @WebServlet annotation is used to define a servlet component in a web application. This annotation is specified on a class and contains metadata about the servlet that is being declared.

Service Methods 

The Generic Servlet provides the service in doMethods. The doMethod can be a method that can be Get, Post, Delete, Put, Trace or Options. The term service method is used for any method in a servlet class that provides a service to a client. The request and response objects are passed as parameters to the doMethods. 

For protocol-specific Servlet class, like HttpServlet protocol-specific request and response objects are passed. The service method fetches the data from the request object, accesses the external resources (like Database) and finally encodes the response based upon the request data. The response occurs as in the following order,

  1. Fetch an output stream from the response.
  2. Fill in the response headers.
  3. Write body content to the output stream.

Response headers must always be set before the response has been committed. The application server will not execute any attempt to set or add headers after the response has been committed. We have selected the doGet(HttpServletRequest, HttpServletResponse) method in our example. In the example below "Hello World" is printed by the doGet() method.



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

            PrintWriter pout=response.getWriter();
            response.setContentType("text/html");
pout.append("<html><body><h1>Hello World</h1></body></html>");//embed HTML within Java

      }


The PrintWriter class is the subclass of Writer class for, character stream IO. This class gives the formatted data as the character output stream.

Complete Servlet Class


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

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

    public MyServlet() {//Constructor
        super();
   
    }

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

            response.getWriter().append("Served at: ").append(request.getContextPath());
            PrintWriter pout=response.getWriter();
            response.setContentType("text/html");
pout.append("<html><body><h1>Hello World</h1></body></html>");
     //embed HTML within Java
      }

}



Running the Servlet

To run the code, right-click on the Servlet code, run as->run on the server
Select the server, if required click next to execute,

running a servlet

It will take a bit of time to load, compile and execute.

Result



Video Tutorial