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
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Java Servlet API

The Java Servlet API is a comprehensive framework for building web applications in Java. It provides a complete set of interfaces and classes for handling HTTP requests, managing sessions, implementing security, and building scalable web applications. The API consists of 77 components across 4 packages, offering both traditional synchronous and modern asynchronous processing capabilities.

Package Information

Maven Dependency:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

Java Version: Requires Java 8 or higher Servlet Specification: Based on Java EE 8 / Jakarta EE 8 specification Container Support: Works with all major servlet containers (Tomcat, Jetty, GlassFish, WebLogic, etc.)

Core Imports

// Core servlet interfaces
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.GenericServlet;

// HTTP-specific interfaces and classes
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Cookie;

// Filter interfaces
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;

// Async processing
import javax.servlet.AsyncContext;
import javax.servlet.AsyncListener;

// Input/Output streams
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;

// Annotations (Servlet 3.0+)
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebListener;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.MultipartConfig;

// Event listeners
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionListener;

Basic Usage

Simple HTTP Servlet

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Basic servlet handling GET and POST requests
 */
@WebServlet(name = "HelloServlet", urlPatterns = {"/hello", "/greeting"})
public class HelloServlet extends HttpServlet {
    
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // Set response content type
        response.setContentType("text/html;charset=UTF-8");
        
        // Get request parameters
        String name = request.getParameter("name");
        if (name == null) {
            name = "World";
        }
        
        // Write response
        try (PrintWriter out = response.getWriter()) {
            out.println("&lt;html&gt;");
            out.println("&lt;head&gt;&lt;title&gt;Hello Servlet&lt;/title&gt;&lt;/head&gt;");
            out.println("&lt;body&gt;");
            out.println("&lt;h1&gt;Hello " + name + "!&lt;/h1&gt;");
            out.println("&lt;/body&gt;&lt;/html&gt;");
        }
    }
    
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
}

Basic Filter

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Basic request logging filter
 */
@WebFilter(filterName = "LoggingFilter", urlPatterns = {"/*"})
public class LoggingFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Initialize filter
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, 
                        FilterChain chain) throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        
        // Log the request
        System.out.println("Request: " + httpRequest.getMethod() + 
                          " " + httpRequest.getRequestURL());
        
        // Continue the chain
        chain.doFilter(request, response);
        
        // Log after processing
        System.out.println("Response sent for: " + httpRequest.getRequestURL());
    }
    
    @Override
    public void destroy() {
        // Clean up resources
    }
}

Architecture

The Java Servlet API is organized into four main packages:

Package Structure

  1. javax.servlet (41 components) - Core servlet functionality

    • Base servlet and filter interfaces
    • Request/response abstractions
    • Context and configuration management
    • Asynchronous processing support
  2. javax.servlet.http (26 components) - HTTP-specific extensions

    • HTTP servlet implementations
    • Session management
    • Cookie handling
    • HTTP/2 server push support
  3. javax.servlet.annotation (7 components) - Declarative configuration

    • Annotation-based servlet configuration
    • Security constraint annotations
    • Initialization parameter annotations
  4. javax.servlet.descriptor (3 components) - Deployment descriptor access

    • Programmatic access to web.xml configuration
    • JSP configuration descriptors

Core Components

/**
 * Core servlet lifecycle interface - all servlets must implement this
 */
public interface Servlet {
    void init(ServletConfig config) throws ServletException;
    ServletConfig getServletConfig();
    void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
    String getServletInfo();
    void destroy();
}

/**
 * HTTP-specific servlet base class
 */
public abstract class HttpServlet extends GenericServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
    protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
    protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
}

/**
 * Filter interface for request/response processing
 */
public interface Filter {
    void init(FilterConfig filterConfig) throws ServletException;
    void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
        throws IOException, ServletException;
    void destroy();
}

Core Servlet Lifecycle and Configuration

Servlet Lifecycle and Configuration - Complete coverage of servlet initialization, configuration, context management, and deployment patterns.

Key APIs covered:

  • Servlet, ServletConfig, ServletContext interfaces
  • GenericServlet and lifecycle management
  • Context attributes and initialization parameters
  • ServletContainerInitializer for programmatic configuration
  • Registration APIs for dynamic servlet/filter setup
// Basic servlet lifecycle
public class MyServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        // Servlet initialization logic
        ServletContext context = getServletContext();
        String initParam = getInitParameter("configParam");
    }
}

HTTP Request and Response Processing

HTTP Request and Response Processing - Comprehensive HTTP handling including request parsing, response generation, headers, parameters, and advanced features.

Key APIs covered:

  • HttpServletRequest and HttpServletResponse interfaces
  • HTTP method handling (doGet, doPost, etc.)
  • Request parameters, headers, and attributes
  • Response status codes, headers, and output streams
  • Multipart request processing and file uploads
  • HTTP/2 server push with PushBuilder
// HTTP request/response processing
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
    
    // Process request parameters
    String param = request.getParameter("data");
    Part filePart = request.getPart("file");
    
    // Set response
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/json");
    response.getWriter().write("{\"status\":\"success\"}");
}

Session Management and Cookies

Session Management and Cookies - Complete session lifecycle, cookie management, session tracking modes, and security considerations.

Key APIs covered:

  • HttpSession interface and session lifecycle
  • Cookie class for client-side state management
  • Session tracking modes (cookies, URL rewriting, SSL)
  • SessionCookieConfig for session cookie configuration
  • Session security and timeout management
// Session and cookie management
HttpSession session = request.getSession();
session.setAttribute("user", currentUser);

Cookie userCookie = new Cookie("username", user.getName());
userCookie.setMaxAge(3600);
userCookie.setHttpOnly(true);
response.addCookie(userCookie);

Asynchronous Processing and I/O

Asynchronous Processing and I/O - Modern async servlet processing, non-blocking I/O, and scalable request handling patterns.

Key APIs covered:

  • AsyncContext for asynchronous request processing
  • ReadListener and WriteListener for non-blocking I/O
  • ServletInputStream and ServletOutputStream async methods
  • AsyncListener for async event handling
  • Thread management and async dispatch
// Asynchronous processing
@WebServlet(asyncSupported = true)
public class AsyncServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        AsyncContext asyncContext = request.startAsync();
        asyncContext.setTimeout(30000);
        
        asyncContext.start(() -> {
            // Long-running operation
            processRequestAsync(asyncContext);
        });
    }
}

Security and Filtering

Security and Filtering - Comprehensive security framework including authentication, authorization, filters, and security constraints.

Key APIs covered:

  • Security constraint annotations (@ServletSecurity, @HttpConstraint)
  • Filter chain processing and security filters
  • Authentication and role-based authorization
  • Transport security and HTTPS enforcement
  • RequestDispatcher for forwarding and including
// Security configuration
@ServletSecurity(
    @HttpConstraint(rolesAllowed = {"admin", "user"}),
    httpMethodConstraints = {
        @HttpMethodConstraint(value = "DELETE", rolesAllowed = {"admin"})
    }
)
public class SecureServlet extends HttpServlet {
    // Servlet implementation
}

Listeners and Events

Listeners and Events - Complete event handling system for application lifecycle, session events, and attribute changes.

Key APIs covered:

  • Context lifecycle listeners (ServletContextListener)
  • Session lifecycle listeners (HttpSessionListener, HttpSessionActivationListener)
  • Attribute change listeners for contexts, sessions, and requests
  • Event objects and listener registration
  • Application startup and shutdown handling
// Event listeners
@WebListener
public class AppLifecycleListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // Application startup logic
        ServletContext context = sce.getServletContext();
        initializeApplication(context);
    }
}

Component Summary

The Java Servlet API provides 77 components organized by functionality:

  • Interfaces: 44 (57%) - Core contracts and extension points
  • Classes: 26 (34%) - Base implementations and utilities
  • Enums: 4 (5%) - Type-safe constants and options
  • Annotations: 9 (12%) - Declarative configuration support

Key Features

  • Complete HTTP Support: Full HTTP/1.1 and HTTP/2 compatibility
  • Asynchronous Processing: Non-blocking I/O and async request handling
  • Security Framework: Comprehensive authentication and authorization
  • Session Management: Robust session lifecycle and state management
  • Event-Driven Architecture: Extensive listener interfaces for lifecycle events
  • Filter Chain: Powerful request/response processing pipeline
  • Annotation Configuration: Modern declarative configuration alongside XML
  • Multipart Processing: Built-in support for file uploads and form data
  • Container Integration: Works with all major Java web containers

The API supports both traditional servlet patterns and modern async/reactive approaches, making it suitable for a wide range of web application architectures from simple web services to complex enterprise applications.

docs

async-processing.md

http-processing.md

index.md

listeners-events.md

security-filtering.md

servlet-lifecycle.md

session-cookies.md

tile.json