CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-javax-servlet--javax-servlet-api

Java Servlet API specification defining core interfaces and classes for web application development

Pending
Overview
Eval results
Files

servlet-lifecycle.mddocs/

Servlet Lifecycle and Configuration

The Java Servlet API provides a comprehensive framework for servlet lifecycle management and configuration. This covers servlet initialization, context management, programmatic configuration, and deployment patterns.

Core Servlet Interface

/**
 * The fundamental servlet interface that all servlets must implement.
 * Defines the contract for servlet lifecycle and request processing.
 */
public interface Servlet {
    /**
     * Initialize the servlet with configuration parameters.
     * Called once when the servlet is first loaded.
     */
    void init(ServletConfig config) throws ServletException;
    
    /**
     * Get the servlet configuration object.
     */
    ServletConfig getServletConfig();
    
    /**
     * Process a request and generate a response.
     * Called for each request to this servlet.
     */
    void service(ServletRequest req, ServletResponse res) 
        throws ServletException, IOException;
    
    /**
     * Return information about the servlet (version, author, etc.)
     */
    String getServletInfo();
    
    /**
     * Cleanup resources when servlet is destroyed.
     * Called once when servlet is removed from service.
     */
    void destroy();
}

ServletConfig Interface

/**
 * Configuration interface providing servlet initialization parameters
 * and access to the servlet context.
 */
public interface ServletConfig {
    /**
     * Get the name of this servlet instance.
     */
    String getServletName();
    
    /**
     * Get the servlet context for the web application.
     */
    ServletContext getServletContext();
    
    /**
     * Get the value of a servlet initialization parameter.
     */
    String getInitParameter(String name);
    
    /**
     * Get an enumeration of all initialization parameter names.
     */
    Enumeration<String> getInitParameterNames();
}

ServletContext Interface

/**
 * Interface representing the web application context.
 * Provides access to application-wide resources and configuration.
 */
public interface ServletContext {
    
    // Context path and version information
    String getContextPath();
    ServletContext getContext(String uripath);
    int getMajorVersion();
    int getMinorVersion();
    int getEffectiveMajorVersion();
    int getEffectiveMinorVersion();
    
    // MIME type support
    String getMimeType(String file);
    
    // Resource access
    Set<String> getResourcePaths(String path);
    URL getResource(String path) throws MalformedURLException;
    InputStream getResourceAsStream(String path);
    RequestDispatcher getRequestDispatcher(String path);
    RequestDispatcher getNamedDispatcher(String name);
    
    // Logging
    void log(String msg);
    void log(String message, Throwable throwable);
    
    // Real paths and server info
    String getRealPath(String path);
    String getServerInfo();
    
    // Context initialization parameters
    String getInitParameter(String name);
    Enumeration<String> getInitParameterNames();
    boolean setInitParameter(String name, String value);
    
    // Context attributes
    Object getAttribute(String name);
    Enumeration<String> getAttributeNames();
    void setAttribute(String name, Object object);
    void removeAttribute(String name);
    
    // Servlet name
    String getServletContextName();
    
    // Dynamic servlet registration
    ServletRegistration.Dynamic addServlet(String servletName, String className);
    ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet);
    ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass);
    <T extends Servlet> T createServlet(Class<T> clazz) throws ServletException;
    ServletRegistration getServletRegistration(String servletName);
    Map<String, ? extends ServletRegistration> getServletRegistrations();
    
    // Dynamic filter registration  
    FilterRegistration.Dynamic addFilter(String filterName, String className);
    FilterRegistration.Dynamic addFilter(String filterName, Filter filter);
    FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass);
    <T extends Filter> T createFilter(Class<T> clazz) throws ServletException;
    FilterRegistration getFilterRegistration(String filterName);
    Map<String, ? extends FilterRegistration> getFilterRegistrations();
    
    // Session configuration
    SessionCookieConfig getSessionCookieConfig();
    void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes);
    Set<SessionTrackingMode> getDefaultSessionTrackingModes();
    Set<SessionTrackingMode> getEffectiveSessionTrackingModes();
    
    // Event listener management
    void addListener(String className);
    <T extends EventListener> void addListener(T t);
    void addListener(Class<? extends EventListener> listenerClass);
    <T extends EventListener> T createListener(Class<T> clazz) throws ServletException;
    
    // JSP support
    JspConfigDescriptor getJspConfigDescriptor();
    
    // Class loader
    ClassLoader getClassLoader();
    
    // Declaration configuration
    void declareRoles(String... roleNames);
    
    // Virtual server name
    String getVirtualServerName();
    
    // Constants
    public static final String TEMPDIR = "javax.servlet.context.tempdir";
    public static final String ORDERED_LIBS = "javax.servlet.context.orderedLibs";
}

GenericServlet Base Class

/**
 * Abstract base class providing default implementations for the Servlet interface.
 * Implements ServletConfig methods by delegating to the actual config object.
 */
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
    
    private transient ServletConfig config;
    
    /**
     * Initialize the servlet and store the config.
     */
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }
    
    /**
     * Convenience init method for subclasses to override.
     */
    public void init() throws ServletException {
        // Default implementation does nothing
    }
    
    /**
     * Abstract service method that subclasses must implement.
     */
    public abstract void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException;
    
    // ServletConfig delegation methods
    public String getServletName() {
        return config.getServletName();
    }
    
    public ServletContext getServletContext() {
        return config.getServletContext();
    }
    
    public String getInitParameter(String name) {
        return config.getInitParameter(name);
    }
    
    public Enumeration<String> getInitParameterNames() {
        return config.getInitParameterNames();
    }
    
    public ServletConfig getServletConfig() {
        return config;
    }
    
    /**
     * Log a message to the servlet context log.
     */
    public void log(String msg) {
        getServletContext().log(getServletName() + ": " + msg);
    }
    
    public void log(String message, Throwable t) {
        getServletContext().log(getServletName() + ": " + message, t);
    }
    
    public String getServletInfo() {
        return "";
    }
    
    public void destroy() {
        // Default implementation does nothing
    }
}

Servlet Registration Interfaces

/**
 * Base interface for servlet and filter registration.
 */
public interface Registration {
    String getName();
    String getClassName();
    boolean setInitParameter(String name, String value);
    String getInitParameter(String name);
    Set<String> setInitParameters(Map<String, String> initParameters);
    Map<String, String> getInitParameters();
    
    /**
     * Dynamic registration interface for runtime configuration changes.
     */
    public interface Dynamic extends Registration {
        void setAsyncSupported(boolean isAsyncSupported);
    }
}

/**
 * Servlet-specific registration interface.
 */
public interface ServletRegistration extends Registration {
    
    /**
     * Add servlet mappings for URL patterns.
     */
    Set<String> addMapping(String... urlPatterns);
    
    /**
     * Get all URL mappings for this servlet.
     */
    Collection<String> getMappings();
    
    /**
     * Get the run-as role for this servlet.
     */
    String getRunAsRole();
    
    /**
     * Dynamic servlet registration interface.
     */
    public interface Dynamic extends ServletRegistration, Registration.Dynamic {
        void setLoadOnStartup(int loadOnStartup);
        Set<String> setServletSecurity(ServletSecurityElement constraint);
        void setMultipartConfig(MultipartConfigElement multipartConfig);
        void setRunAsRole(String roleName);
    }
}

/**
 * Filter-specific registration interface.
 */
public interface FilterRegistration extends Registration {
    
    /**
     * Add filter mappings for URL patterns.
     */
    void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, 
                                 boolean isMatchAfter, String... urlPatterns);
    
    /**
     * Add filter mappings for servlet names.
     */
    void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, 
                                  boolean isMatchAfter, String... servletNames);
    
    /**
     * Get URL pattern mappings.
     */
    Collection<String> getUrlPatternMappings();
    
    /**
     * Get servlet name mappings.
     */
    Collection<String> getServletNameMappings();
    
    /**
     * Dynamic filter registration interface.
     */
    public interface Dynamic extends FilterRegistration, Registration.Dynamic {
        // Inherits all methods from parent interfaces
    }
}

ServletContainerInitializer

/**
 * Interface for programmatic servlet container initialization.
 * Implementations are discovered via ServiceLoader during container startup.
 */
public interface ServletContainerInitializer {
    
    /**
     * Called during container startup to perform programmatic configuration.
     * 
     * @param c Set of classes that this initializer expressed interest in
     * @param ctx The servlet context for programmatic configuration
     */
    void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException;
}

Configuration Examples

Programmatic Servlet Configuration

/**
 * Example ServletContainerInitializer for programmatic configuration
 */
@HandlesTypes({Servlet.class, Filter.class})
public class MyAppInitializer implements ServletContainerInitializer {
    
    @Override
    public void onStartup(Set<Class<?>> classes, ServletContext ctx) throws ServletException {
        
        // Add a servlet programmatically
        ServletRegistration.Dynamic servlet = ctx.addServlet("MyServlet", MyServlet.class);
        servlet.addMapping("/api/*");
        servlet.setLoadOnStartup(1);
        servlet.setAsyncSupported(true);
        servlet.setInitParameter("config", "production");
        
        // Add a filter programmatically
        FilterRegistration.Dynamic filter = ctx.addFilter("MyFilter", MyFilter.class);
        filter.addMappingForUrlPatterns(
            EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), 
            true, "/*"
        );
        filter.setAsyncSupported(true);
        
        // Add listeners
        ctx.addListener(MyContextListener.class);
        ctx.addListener(MySessionListener.class);
        
        // Configure session tracking
        ctx.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE));
        
        SessionCookieConfig cookieConfig = ctx.getSessionCookieConfig();
        cookieConfig.setName("JSESSIONID");
        cookieConfig.setHttpOnly(true);
        cookieConfig.setSecure(true);
        cookieConfig.setMaxAge(-1);
        cookieConfig.setPath(ctx.getContextPath());
    }
}

Annotation-Based Configuration

/**
 * Servlet configured using annotations
 */
@WebServlet(
    name = "ConfiguredServlet",
    urlPatterns = {"/config", "/setup"},
    loadOnStartup = 1,
    initParams = {
        @WebInitParam(name = "database.url", value = "jdbc:mysql://localhost/mydb"),
        @WebInitParam(name = "pool.size", value = "10")
    },
    asyncSupported = true,
    description = "Example configured servlet"
)
public class ConfiguredServlet extends HttpServlet {
    
    private String databaseUrl;
    private int poolSize;
    
    @Override
    public void init() throws ServletException {
        // Access initialization parameters
        databaseUrl = getInitParameter("database.url");
        poolSize = Integer.parseInt(getInitParameter("pool.size"));
        
        // Access servlet context
        ServletContext context = getServletContext();
        context.setAttribute("servlet.config", this);
        
        log("Servlet initialized with database URL: " + databaseUrl);
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        
        out.println("{");
        out.println("  \"servlet\": \"" + getServletName() + "\",");
        out.println("  \"database\": \"" + databaseUrl + "\",");
        out.println("  \"poolSize\": " + poolSize);
        out.println("}");
    }
    
    @Override
    public void destroy() {
        // Cleanup resources
        ServletContext context = getServletContext();
        context.removeAttribute("servlet.config");
        log("Servlet destroyed");
    }
}

WebInitParam Annotation

/**
 * Annotation used to specify initialization parameters for servlets and filters
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface WebInitParam {
    
    /**
     * Name of the initialization parameter
     * @return parameter name
     */
    String name();
    
    /**
     * Value of the initialization parameter
     * @return parameter value
     */
    String value();
    
    /**
     * Description of the initialization parameter
     * @return parameter description
     */
    String description() default "";
}

Context Attributes and Application State

/**
 * Example servlet demonstrating context attribute management
 */
public class StateManagementServlet extends HttpServlet {
    
    @Override
    public void init() throws ServletException {
        ServletContext context = getServletContext();
        
        // Initialize application-wide state
        Map<String, Object> appConfig = new ConcurrentHashMap<>();
        appConfig.put("startTime", System.currentTimeMillis());
        appConfig.put("version", "1.0.0");
        context.setAttribute("app.config", appConfig);
        
        // Initialize counters
        AtomicLong requestCounter = new AtomicLong(0);
        context.setAttribute("request.counter", requestCounter);
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        ServletContext context = getServletContext();
        
        // Access application state
        Map<String, Object> appConfig = 
            (Map<String, Object>) context.getAttribute("app.config");
        AtomicLong counter = 
            (AtomicLong) context.getAttribute("request.counter");
        
        long currentRequest = counter.incrementAndGet();
        long startTime = (Long) appConfig.get("startTime");
        long uptime = System.currentTimeMillis() - startTime;
        
        // Generate response
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        
        out.println("{");
        out.println("  \"requestNumber\": " + currentRequest + ",");
        out.println("  \"uptimeMs\": " + uptime + ",");
        out.println("  \"version\": \"" + appConfig.get("version") + "\",");
        out.println("  \"contextPath\": \"" + context.getContextPath() + "\",");
        out.println("  \"serverInfo\": \"" + context.getServerInfo() + "\"");
        out.println("}");
    }
}

Multi-Config Element Support

/**
 * Configuration element for multipart request handling
 */
public class MultipartConfigElement {
    
    private final String location;
    private final long maxFileSize;
    private final long maxRequestSize;
    private final int fileSizeThreshold;
    
    public MultipartConfigElement(String location) {
        this(location, -1L, -1L, 0);
    }
    
    public MultipartConfigElement(String location, long maxFileSize, 
                                 long maxRequestSize, int fileSizeThreshold) {
        this.location = location;
        this.maxFileSize = maxFileSize;
        this.maxRequestSize = maxRequestSize;
        this.fileSizeThreshold = fileSizeThreshold;
    }
    
    /**
     * Get the directory location where files will be stored.
     */
    public String getLocation() {
        return location;
    }
    
    /**
     * Get the maximum size allowed for uploaded files.
     * -1 means unlimited.
     */
    public long getMaxFileSize() {
        return maxFileSize;
    }
    
    /**
     * Get the maximum size allowed for multipart/form-data requests.
     * -1 means unlimited.
     */
    public long getMaxRequestSize() {
        return maxRequestSize;
    }
    
    /**
     * Get the size threshold after which files will be written to disk.
     */
    public int getFileSizeThreshold() {
        return fileSizeThreshold;
    }
}

Dispatcher Types Enum

/**
 * Enumeration of dispatcher types for filter mapping
 */
public enum DispatcherType {
    
    /**
     * Request came directly from the client (normal request)
     */
    REQUEST,
    
    /**
     * Request is being forwarded to another resource
     */
    FORWARD,
    
    /**
     * Request is including another resource
     */
    INCLUDE,
    
    /**
     * Request is being processed asynchronously
     */
    ASYNC,
    
    /**
     * Request is being processed due to an error
     */
    ERROR
}

Lifecycle Management Patterns

Servlet Lifecycle States

/**
 * Complete servlet lifecycle example showing all phases
 */
public class LifecycleServlet extends HttpServlet {
    
    private boolean initialized = false;
    private long initTime;
    private AtomicLong requestCount = new AtomicLong(0);
    
    /**
     * Initialization phase - called once when servlet is loaded
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        
        initTime = System.currentTimeMillis();
        
        // Perform initialization logic
        String configParam = getInitParameter("config.param");
        if (configParam != null) {
            // Process configuration
        }
        
        // Mark as initialized
        initialized = true;
        
        log("Servlet initialized at " + new Date(initTime));
    }
    
    /**
     * Service phase - called for each request
     */
    @Override
    public void service(ServletRequest req, ServletResponse res) 
            throws ServletException, IOException {
        
        if (!initialized) {
            throw new ServletException("Servlet not properly initialized");
        }
        
        long requestNumber = requestCount.incrementAndGet();
        log("Processing request #" + requestNumber);
        
        // Delegate to HTTP-specific methods
        super.service(req, res);
    }
    
    /**
     * Destruction phase - called once when servlet is unloaded
     */
    @Override
    public void destroy() {
        log("Destroying servlet after " + requestCount.get() + " requests");
        
        // Cleanup resources
        initialized = false;
        requestCount.set(0);
        
        // Perform cleanup logic
        cleanupResources();
    }
    
    private void cleanupResources() {
        // Close database connections, file handles, etc.
    }
    
    @Override
    public String getServletInfo() {
        return "Lifecycle demonstration servlet v1.0";
    }
}

JSP Configuration Descriptors

The servlet API provides programmatic access to JSP-related configuration through deployment descriptor interfaces.

JspConfigDescriptor Interface

/**
 * Provides access to JSP-related configuration from web.xml and web-fragment.xml
 */
public interface JspConfigDescriptor {
    
    /**
     * Gets taglib child elements of the jsp-config element
     * @return Collection of TaglibDescriptor objects
     */
    Collection<TaglibDescriptor> getTaglibs();
    
    /**
     * Gets jsp-property-group child elements of the jsp-config element  
     * @return Collection of JspPropertyGroupDescriptor objects
     */
    Collection<JspPropertyGroupDescriptor> getJspPropertyGroups();
}

TaglibDescriptor Interface

/**
 * Provides access to taglib configuration from deployment descriptors
 */
public interface TaglibDescriptor {
    
    /**
     * Gets the unique identifier of the tag library
     * @return the taglib URI
     */
    String getTaglibURI();
    
    /**
     * Gets the location of the tag library
     * @return the taglib location
     */
    String getTaglibLocation();
}

JspPropertyGroupDescriptor Interface

/**
 * Provides access to JSP property group configuration from deployment descriptors
 */
public interface JspPropertyGroupDescriptor {
    
    /**
     * Gets URL patterns of the JSP property group
     * @return Collection of URL patterns
     */
    Collection<String> getUrlPatterns();
    
    /**
     * Gets el-ignored configuration value
     * @return el-ignored value or null if unspecified
     */
    String getElIgnored();
    
    /**
     * Gets page-encoding configuration value
     * @return page encoding or null if unspecified
     */
    String getPageEncoding();
    
    /**
     * Gets scripting-invalid configuration value
     * @return scripting-invalid value or null if unspecified
     */
    String getScriptingInvalid();
    
    /**
     * Gets is-xml configuration value
     * @return is-xml value or null if unspecified
     */
    String getIsXml();
    
    /**
     * Gets include-prelude configuration
     * @return Collection of include-prelude values
     */
    Collection<String> getIncludePreludes();
    
    /**
     * Gets include-coda configuration
     * @return Collection of include-coda values
     */
    Collection<String> getIncludeCodas();
    
    /**
     * Gets deferred-syntax-allowed-as-literal configuration value
     * @return deferred-syntax-allowed-as-literal value or null if unspecified
     */
    String getDeferredSyntaxAllowedAsLiteral();
    
    /**
     * Gets trim-directive-whitespaces configuration value
     * @return trim-directive-whitespaces value or null if unspecified
     */
    String getTrimDirectiveWhitespaces();
    
    /**
     * Gets default-content-type configuration value
     * @return default content type or null if unspecified
     */
    String getDefaultContentType();
    
    /**
     * Gets buffer configuration value
     * @return buffer value or null if unspecified
     */
    String getBuffer();
    
    /**
     * Gets error-on-undeclared-namespace configuration value
     * @return error-on-undeclared-namespace value or null if unspecified
     */
    String getErrorOnUndeclaredNamespace();
}

This comprehensive coverage of servlet lifecycle and configuration provides the foundation for understanding how servlets are initialized, configured, and managed throughout their lifetime in the container.

Install with Tessl CLI

npx tessl i tessl/maven-javax-servlet--javax-servlet-api

docs

async-processing.md

http-processing.md

index.md

listeners-events.md

security-filtering.md

servlet-lifecycle.md

session-cookies.md

tile.json