Servlet

A Servlet is an object that receives a request and generates a response based on that request.

To deploy and run a servlet, a web container must be used such as TomCat/JWS/Jetty/Resin.

In order to create a servlet the class must extend servlet.

The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet elements, including session management objects that track multiple requests and responses between the web server and a client. Servlets may be packaged in a WAR file as a web application.

Servlets can be generated automatically from JavaServer Pages (JSP) by the JavaServer Pages compiler.

The difference between servlets and JSP is that servlets typically embed HTML inside Java code, while JSPs embed Java code in HTML.

The Java servlet API has, to some extent, been superseded by two standard Java technologies for web services: jax-rs , and  jax-ws

 

GenericServlet abstract class – is based upon the Servlet interface and supports all protocols(HTTP,SMTP,FTP etc..). Service method will called by the servlet container when a request arrives.

HttpServlet abstract class is a subclass of GenericServlet and supports only http verb protocols (doPost or doPut or doGet etc..) that are called upon request by the servlet container. It also extends the GenericServlet and add’s on to it session data.

 

Example of GenericServlet implementation(with the service method):

import java.io.*;
import javax.servlet.*;

public class SampleGenericServlet extends GenericServlet{
 public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
  
 res.setContentType("text/html");
   PrintWriter pwriter=res.getWriter();
   pwriter.print("<html>");
   pwriter.print("<body>");
   pwriter.print("<h2>Generic Servlet Example</h2>");
   pwriter.print("<p>Hello Readers!</p>");
   pwriter.print("</body>");
   pwriter.print("</html>");
 }
}