🌐

Understanding Servlets and Their Containers

Aug 8, 2024

Servlet and Servlet Container

Overview

  • Servlets are server-side Java classes that handle requests from a browser.
  • A servlet container is required to run these servlets and process HTTP requests.

Role of Servlet Container

  • The servlet container reads data sent from the browser.
  • Only servlet classes can read this data due to container permissions.
  • The servlet container executes servlets based on HTTP requests.

How Servlet Processing Works

  1. Receiving Data

    • Data is sent from the browser to the server using the HTTP protocol.
    • HTTP protocol consists of headers and body (query strings and payload).
  2. Converting Data

    • The servlet container receives the HTTP data and converts it into an HTTP servlet request object (HttpServletRequest).
    • This object stores the data for further processing.
  3. Forwarding Data

    • The request object is forwarded to the appropriate servlet for processing.
    • The servlet container determines which servlet to execute based on the URL.

URL and Servlet Mapping

  • The URL determines which servlet class to invoke.
  • Example URL format: http://localhost:8080/myapp/servletName
  • Each servlet can be mapped to a specific URL path.

Submitting Form Data

  • Form data submitted from the browser is sent to servlet using an action attribute in the form tag.
  • The data can be sent as either a query string (GET method) or in the body (POST method) depending on the form method.

Example of Form Submission

<form action="http://localhost:8080/myapp/servletName" method="GET"> <input type="text" name="paramName" /> <input type="submit" value="Submit" /> </form>

Execution of Servlets

  • The first time a servlet is requested, the servlet container creates an instance of the servlet class (singleton pattern).
  • Once the object is created, it can process incoming requests using defined methods.

Important Terms

  • HttpServletRequest: Object containing request data sent from the browser.
  • HttpServletResponse: Object for sending a response back to the client.
  • URL Mapping: Process of connecting specific URLs to designated servlets.