Servlets

Servlets



1. What is a Servlet?

A Servlet is a Java class used to extend the capabilities of a server that hosts applications accessed via a request-response programming model.


  • Runs on a web server or application server (e.g., Apache Tomcat).
  • Handles HTTP requests (GET, POST, PUT, DELETE) and generates dynamic responses (HTML, JSON, XML).
  • Acts as the Controller layer in traditional Model-View-Controller (MVC) architecture.



2. Servlet Architecture & Hierarchy

Servlets belong to the jakarta.servlet package (formerly javax.servlet).


Servlet (Interface)
│
GenericServlet (Abstract Class)
│
HttpServlet (Abstract Class)
│
YourCustomServlet (Concrete Class)

  • Servlet Interface: Defines the core lifecycle methods.
  • GenericServlet: Protocol-independent servlet implementation.
  • HttpServlet: Provides HTTP-specific processing (doGet, doPost, etc.).



3. Servlet Lifecycle

Managed entirely by the Servlet Container (e.g., Tomcat):


  1. Loading & Instantiation: Container loads the servlet class and creates an instance.
  2. Initialization (init()): Called once when the servlet is created. Used for setup tasks (database connection setup, config loading).
  3. Request Handling (service()): Called for every incoming request. Routes requests to specific methods like doGet() or doPost().
  4. Destruction (destroy()): Called once before the servlet is removed from memory. Used for cleanup.



4. Key Request Handling Methods

In an HttpServlet, you override specific methods depending on HTTP operations:


  • doGet(HttpServletRequest req, HttpServletResponse resp): Handles GET requests (retrieving data, rendering pages).
  • doPost(HttpServletRequest req, HttpServletResponse resp): Handles POST requests (form submissions, sending sensitive/bulk data).
  • doPut(), doDelete(): Handle RESTful updates and deletions.



5. Key Objects


  • HttpServletRequest: Provides access to client request data (form parameters, HTTP headers, cookies, request attributes).
  • HttpServletResponse: Used to configure and send response data back to the client (content type, status codes, output stream/writer).
  • ServletContext: Shared context across the entire application (global parameters, application attributes).
  • ServletConfig: Servlet-specific initialization configuration defined in web.xml or annotations.
Code Snippets 3
Basic Servlet Example
Basic


1. Download tomcat from link here
if link doesnt work use Link here

Servlets can be configured in two ways :
1. Annotations (Modern approach): @WebServlet("/path") placed above the servlet class.
2. XML Deployment Descriptor ( web.xml - Traditional approach):



<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.example.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

package com.vs;
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("/GreetingServlet") public class GreetingServlet extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }
}

ServletInfo
Basic

Create a new Java class named ServerInfoServlet.java inside your project's src/main/java directory (under an appropriate package):

package com.vs;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
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("/server-info") public class ServerInfoServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try(PrintWriter out = response.getWriter()) {
      out.println("<!DOCTYPE html>");
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Server Information</title>");
      out.println("<style>");
      out.println("body { font-family: Arial, sans-serif; margin: 40px; background-color: #f9f9f9; }");
      out.println("h2 { color: #333; }");
      out.println("ul { background: #fff; padding: 20px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); list-style-type: none; }");
      out.println("li { padding: 8px 0; border-bottom: 1px solid #eee; }");
      out.println("li:last-child { border-bottom: none; }");
      out.println("</style>");
      out.println("</head>");
      out.println("<body>");
      out.println("<h2>Tomcat & Environment Details</h2>");
      out.println("<ul>");
      out.println("<li><b>Servlet Container:</b> " + getServletContext().getServerInfo() + "</li>");
      out.println("<li><b>Servlet API Version:</b> " + getServletContext().getMajorVersion() + "." + getServletContext().getMinorVersion() + "</li>");
      out.println("<li><b>Java Version:</b> " + System.getProperty("java.version") + "</li>");
      out.println("<li><b>Operating System:</b> " + System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ")</li>");
      out.println("<li><b>Current Server Time:</b> " + new Date() + "</li>");
      out.println("</ul>");
      out.println("</body>");
      out.println("</html>");
    }
  }
}

Java Bean Example
Basic

Java Bean Example

package com.vs.bean;
public class Employee implements java.io.Serializable {
  private int id;
  private String name;
  public Employee() {
  }
  public void setId(int id) {
    this.id = id;
  }
  public int getId() {
    return id;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getName() {
    return name;
  }
}
//run this in another class
package com.vs.bean;
public class BeanTest {
  public static void main(String args[]) {
    Employee e = new Employee();
    e.setName("Arjun");
    e.setId(1);
    System.out.println(e.getId() + "  " + e.getName());
  }
}
Mindmap Notes
Common issues:
1. tomcat asking to set JAVA_HOME
Solution : put this at the begining of startup.bat SET JAVA_HOME=Path to jdk
2. tomcat not running on default port 8080 (oracle DB might be using it)
Modify in tomcat/conf/server.xml change port 8080 to 9090
Quiz

No quiz for this topic.

Discussion

Login to join the discussion.


No comments yet.