HttpServlet
class or implement the Servlet
interface.load-on-startup
element in web.xml can control this timing.
A positive integer value forces eager loading, with lower numbers loading first.static String myVar1 = "default";
).static { /* initialization code */ }
).init()
Method
init()
method to allow the servlet to perform one-time setup operations.init(ServletConfig config)
- receives configuration information.init()
- convenience method for custom initialization logic.init()
method completes successfully before any requests are processed.
If initialization fails, the servlet becomes unavailable for request processing.ServletException
or UnavailableException
.UnavailableException
allows specifying either permanent unavailability or a temporary duration after which the servlet may be retried.service()
Method
service()
method has two main variants:service(ServletRequest req, ServletResponse res)
- generic servlet interface.service(HttpServletRequest req, HttpServletResponse res)
- HTTP-specific implementation.HttpServlet
class provides a sophisticated implementation that automatically dispatches requests to appropriate handler methods based on the HTTP method (GET, POST, PUT, DELETE, etc.).
This dispatch mechanism eliminates the need for manual method checking in most cases.service()
methoddoXXX()
methodservice()
method from the HttpServlet
class:
package jakarta.servlet.http; public abstract class HttpServlet extends GenericServlet implements Serializable { protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod(); if(method.equals("GET")) { doGet(req, resp); } else if(method.equals("POST")) { doPost(req, resp); } else if(method.equals("HEAD")) { doHead(req, resp); } else if(method.equals("OPTIONS")) { doOptions(req, resp); } else if(method.equals("TRACE")) { doTrace(req, resp); } else if(method.equals("PUT")) { doPut(req, resp); } else if(method.equals("DELETE")) { doDelete(req, resp); } else { sendMethodNotAllowed(req, resp); } } }Thread safety considerations:
destroy()
Method
destroy()
method when it decides to terminate the servlet instance.destroy()
, the container ensures:service()
method have completed.destroy()
method will never be called if the init()
method failed during initialization.
This prevents cleanup operations on improperly initialized servlets.package com.mtitek.servlets.test1; import java.io.IOException; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class MyServlet2 extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException { System.out.println("MyServlet2 : init(ServletConfig) : Start"); super.init(config); System.out.println("MyServlet2 : init(ServletConfig) : End"); } @Override public void init() throws ServletException { System.out.println("MyServlet2 : init() : Start"); super.init(); System.out.println("MyServlet2 : init() : End"); } @Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { System.out.println("MyServlet2 : service(ServletRequest, ServletResponse) : Start"); super.service(request, response); System.out.println("MyServlet2 : service(ServletRequest, ServletResponse) : End"); } @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("MyServlet2 : service(HttpServletRequest, HttpServletResponse)"); } @Override public void destroy() { System.out.println("MyServlet2 : destroy() : Start"); super.destroy(); System.out.println("MyServlet2 : destroy() : End"); } }Console output when the servlet is accessed:
MyServlet2 : init(ServletConfig) : Start MyServlet2 : init() : Start MyServlet2 : init() : End MyServlet2 : init(ServletConfig) : End MyServlet2 : service(ServletRequest, ServletResponse) : Start MyServlet2 : service(HttpServletRequest, HttpServletResponse) MyServlet2 : service(ServletRequest, ServletResponse) : EndThe output demonstrates the method execution order and the inheritance chain behavior where superclass methods are invoked through
super
calls.<servlet>
element using <init-param>
elements, each containing a <param-name>
and <param-value>
pair.
These parameters are read-only and remain constant throughout the servlet's lifecycle.String getInitParameter(String name)
null
if the parameter does not exist.
This method is case-sensitive and returns the exact string value as defined in web.xml.Enumeration<String> getInitParameterNames()
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <servlet> <servlet-name>MyServlet1N1</servlet-name> <servlet-class>com.mtitek.servlets.test1.MyServlet1</servlet-class> <init-param> <param-name>myservlet1n1_param_name_1</param-name> <param-value>myservlet1n1_param_value_1</param-value> </init-param> <init-param> <param-name>myservlet1n1_param_name_2</param-name> <param-value>myservlet1n1_param_value_2</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>MyServlet1N1</servlet-name> <url-pattern>/MyServlet1UP1</url-pattern> </servlet-mapping> </web-app>
package com.mtitek.servlets.test1; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class MyServlet1 extends HttpServlet { @Override public void service( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println( "<html><title>servlet - Hello, world!</title><body>" ); out.println( "<h1>servlet - Hello, world!</h1><hr /><br />" ); out.println( "<b>Servlet Name:</b> " + getServletName() + "<br /><br />"); out.println( "<b>Initialization Parameters:</b><br />"); Enumeration<String> initParameterNames = getInitParameterNames(); if (!initParameterNames.hasMoreElements()) { out.println("No initialization parameters found.<br />"); } else { while (initParameterNames.hasMoreElements()) { String initParameterName = initParameterNames.nextElement(); String initParameterValue = getInitParameter(initParameterName); out.println("<b>" + initParameterName + ":</b> " + initParameterValue + "<br />"); } } out.println( "</body></html>" ); out.close(); } }