Sunday, 23 March 2014

Servlets : Servlet Interface

🚀 Level Up Your Java & Backend Skills!

Enjoying tutorials on Java and Web Development? Subscribe to Ram N Java for more practical guides!

🔔 Subscribe to Ram N Java

What is the Servlet Interface?

In Java Web Development, the Servlet interface is the central abstraction of the entire Servlet API. To build any servlet, your class must implement the javax.servlet.Servlet interface directly or indirectly.

  • Direct Implementation: Create a Java class that explicitly implements Servlet and override all 5 required methods.
  • Indirect Implementation: Extend helper classes like GenericServlet or HttpServlet, which provide default implementations for convenience.

The 5 Methods of the Servlet Interface

The Servlet interface defines 5 core methods categorized into Life Cycle and Non-Life Cycle methods:

1. Life Cycle Methods

  • init(ServletConfig config): Invoked once by the servlet container when the servlet is initialized and ready to be placed into service.
  • service(ServletRequest req, ServletResponse res): Called by the container each time an incoming client request matches the servlet's URL mapping. It processes the request and sends the response back.
  • destroy(): Called once when the servlet container is shutting down or taking the servlet instance out of service.

2. Non-Life Cycle Methods

  • getServletConfig(): Returns the ServletConfig object containing startup and initialization parameters.
  • getServletInfo(): Returns basic metadata such as author, version, and copyright details.

Deployment & Execution Workflow

When a user triggers an action in the browser, the request flows through the web server to the servlet container (such as Apache Tomcat):

  1. The container checks the web.xml mapping to find the matching <url-pattern> and corresponding servlet class.
  2. The class is loaded, instantiated, and initialized via init().
  3. Subsequent requests run through the service() method.
  4. When the server stops, the destroy() method cleans up active resources.

Recommended Related Tutorials

Continue mastering Java Servlets with these hand-picked tutorials from Ram N Java:


Click here to watch in Youtube :  https://www.youtube.com/watch?v=X9AheaJGMBI

Click the below Image to Enlarge
Servlet Interface

ServletInterface Project Dir Structure
Servlet Interface

FirstServlet.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class FirstServlet implements Servlet
{
  ServletConfig config = null;

  public void init( ServletConfig config )
  {
    this.config = config;
    System.out.println("-----------------------------------------------------");
    System.out.println("init method has been called and servlet is initialized");
    System.out.println("-----------------------------------------------------");
  }

  public void service( ServletRequest req, ServletResponse res ) throws IOException, ServletException
  {
    System.out.println("-----------------------------------------------------");
    System.out.println("service method has been called");
    System.out.println("-----------------------------------------------------");

    res.setContentType("text/html");

    PrintWriter out = res.getWriter();
    out.print("<html><body>");
    out.print("<b>hello simple servlet</b>");
    out.print("<br>");
    out.print("<b>Servlet Info :</b> "+getServletInfo());
    out.print("<br>");
    out.print("<b>Get Servlet config object :</b> "+getServletConfig());
    
    out.print("</body></html>");

  }

  public void destroy()
  {
    System.out.println("-----------------------------------------------------");
    System.out.println("destroy method has been called and servlet is destroyed");
    System.out.println("-----------------------------------------------------");
  }

  public ServletConfig getServletConfig()
  {
    return config;
  }

  public String getServletInfo()
  {
    return "copyright 2014-01-01 version : 3.0";
  }

}

Web.xml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 metadata-complete="true" version="3.0">
 <display-name>Servlet Interface</display-name>
 <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>
 <servlet>
  <servlet-name>FirstServlet</servlet-name>
  <servlet-class>FirstServlet</servlet-class>

 </servlet>
 <servlet-mapping>
  <servlet-name>FirstServlet</servlet-name>
  <url-pattern>/firstServlet</url-pattern>
 </servlet-mapping>

</web-app>

index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!DOCTYPE HTML><html lang="en"><head>
<meta charset="UTF-8">
<title>ServletInterface</title>
</head>
<body>
<p>
<h3>ServletInterface</H3>
<p></p>
<ul>

<li><a href="firstServlet">FirstServlet</a></li>

</ul>
</body></html>

Environment Used:

JDK version :1.6.0_30
Tomcat version : 7.0.50 

To Download ServletInterfaceApp Project Click the below link

https://sites.google.com/site/javaee4321/servlets/ServletInterfaceApp.zip?attredirects=0&d=1 
 
See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • 1 comment:

    Tutorials