Showing posts with label Web Architecture. Show all posts
Showing posts with label Web Architecture. Show all posts

Saturday, 22 March 2014

Servlets : How Servlets Works - Flow chart

🚀 Master Java Web Architecture & Servlets!

Want to understand exactly how Java web applications work behind the scenes? Subscribe to Ram N Java for more clear, practical tutorials!

🔔 Subscribe to Ram N Java

Introduction: Behind the Scenes of a Servlet

When a user clicks a button or navigates to a URL on a website, a request travels over the network to the web server. But once it arrives at the Servlet Container (such as Apache Tomcat), what actually happens under the hood?

Understanding the internal lifecycle and thread execution flow helps developers build high-performance web applications and troubleshoot concurrency or state issues with confidence.

The Complete Step-by-Step Servlet Workflow

  1. Client Issues HTTP Request: The browser generates an HTTP request (GET, POST, etc.) and transmits it across the network to the server.
  2. Web Server Routes to Servlet Container: The web server identifies that dynamic processing is required and hands over the raw request bytes to the servlet engine.
  3. Request & Response Object Creation: The container instantiates two key Java objects:
    • HttpServletRequest: Encapsulates incoming parameters, headers, cookies, and payload data.
    • HttpServletResponse: Provides helper methods and output streams to construct the server's reply.
  4. Class Loading & Initialization: If the servlet class has not been loaded previously, the container loads the bytecode, instantiates a single instance, and calls init(ServletConfig).
  5. Thread Allocation & service() Invocation: The container allocates a thread from its thread pool and passes the request and response objects into the servlet's service() method.
  6. Business Logic Execution: The service() method delegates to the appropriate handler (such as doGet() or doPost()), which executes custom business logic and writes data to the response stream.
  7. Response Sent to Client: Once execution finishes, the container packages the HTTP response status code, headers, and body back to the client browser.
  8. Garbage Collection & Destruction: The request and response objects are dereferenced for garbage collection. When the container unloads or shuts down, the servlet's destroy() method executes once.

Single Instance, Multi-Threaded Execution Model

A crucial architectural feature of Java Servlets is their single-instance model:

  • Only one instance of a given servlet class is maintained in memory by default.
  • Each incoming client request is handled by a separate lightweight thread executing the service() method concurrently on that single instance.
  • Best Practice: Avoid declaring mutable instance variables inside servlets to prevent race conditions and thread-safety bugs. Always use local variables within methods whenever possible.

Recommended Related Tutorials

Explore more core Java Servlet internals and features with these hand-picked tutorials from Ram N Java:


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

Click the below Image to Enlarge
How Servlets Works - Flow chart
How Servlets Works - Flow chart
How Servlets Works - Flow chart
How Servlets Works - Flow chart
How Servlets Works - Flow chart
































































See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Wednesday, 5 March 2014

    Servlet Packages

    🚀 Master Java Web Architecture & Servlets!

    Want to build a rock-solid foundation in enterprise Java web development? Subscribe to Ram N Java for more clear, beginner-friendly programming guides!

    🔔 Subscribe to Ram N Java

    Introduction: The Two Core Servlet Packages

    When building server-side applications in Java, the Servlet API provides the standard contract between web containers (like Apache Tomcat) and your custom Java code.

    The entire Java Servlet API is organized primarily into two fundamental packages:

    • javax.servlet (or jakarta.servlet in modern specifications)
    • javax.servlet.http (or jakarta.servlet.http)

    Understanding how these two packages divide responsibilities helps you write clean, modular, and standard-compliant web applications.

    1. The javax.servlet Package (Protocol-Independent)

    The javax.servlet package provides generic, protocol-independent classes and interfaces designed to handle any type of request-response communication:

    • Servlet Interface: The root interface defining lifecycle methods (init(), service(), and destroy()).
    • GenericServlet: An abstract class implementing Servlet that provides basic setup and config handling without assuming HTTP.
    • ServletRequest & ServletResponse: Generic input/output abstractions for reading incoming data and transmitting outgoing payloads.
    • ServletConfig & ServletContext: Interfaces used to access servlet-specific initialization parameters and application-wide contextual parameters.
    • Filter & FilterChain: Components that intercept and transform requests and responses dynamically.

    2. The javax.servlet.http Package (HTTP-Specific)

    Because almost all web communication relies on the HTTP protocol, the javax.servlet.http package extends the generic servlet abstractions to provide rich HTTP-specific features:

    • HttpServlet: An abstract class that extends GenericServlet and automatically routes HTTP requests to dedicated methods such as doGet(), doPost(), doPut(), and doDelete().
    • HttpServletRequest & HttpServletResponse: Sub-interfaces providing HTTP methods, header parsing, cookies access, query strings, and redirect handling.
    • HttpSession: The primary interface for tracking user sessions, managing state across multiple web requests, and handling logins.
    • Cookie: A concrete class representing HTTP cookies exchanged between browser and server.

    Why This Architectural Separation Matters

    Java's architects deliberately decoupled protocol-independent components from HTTP-specific classes:

    1. Flexibility & Extensibility: Java Servlets were designed to theoretically support non-HTTP network protocols (such as FTP or SMTP) using the same core lifecycle.
    2. Clear Separation of Concerns: Developers building web apps can focus directly on HttpServlet while the underlying container manages generic request lifecycles cleanly.
    3. Clean Inheritance Hierarchy: HttpServlet inherits from GenericServlet, allowing HTTP-specific features to layer neatly on top of the generic servlet contract.

    Recommended Related Tutorials

    Expand your knowledge of Java Servlet architecture with these selected tutorials from Ram N Java:



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


    Click the below Image to Enlarge
    Servlet Packages

    Servlet Packages


    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Tuesday, 1 October 2013

    Intercepting Filter Design Pattern - KeyPoints

    🚀 Master Java Enterprise Architecture!

    Subscribe to Ram N Java for clean software design patterns, enterprise Java tutorials, and architecture best practices!

    🔔 Subscribe to Ram N Java

    What Is the Intercepting Filter Design Pattern?

    The Intercepting Filter Design Pattern is an architectural pattern used to intercept incoming HTTP requests and outgoing responses. It enables you to perform pre-processing (such as authentication, authorization, or logging) before a request hits the main target handler, as well as post-processing (such as data compression or encryption) before returning the response to the client.

    Key Takeaways & Core Concepts

    • Centralized Pre/Post Processing: Consolidates cross-cutting concerns (logging, debugging, session validation, encryption) into discrete, reusable filter components rather than cluttering business controllers.
    • Loose Coupling & Modularity: The core target application does not know which filters are running. Filters execute independently and can be added, rearranged, or removed dynamically without touching business logic.
    • Chaining Mechanism: Filters are linked sequentially via a FilterChain. Each filter executes its pre-processing task and then passes the request down the chain to the next filter or target.
    • Declarative Configuration: In enterprise web applications (like Java Servlets and Spring MVC), filters can be declared and ordered declaratively through deployment descriptors or annotations.

    Primary Components in the Architecture

    1. Filter: An individual unit that performs a specific processing task (e.g., AuthenticationFilter, LoggingFilter).
    2. Filter Chain: An ordered collection of filters that coordinates sequential execution before invoking the target.
    3. Filter Manager: Manages filter creation, lifecycle, and creates the appropriate chain for incoming requests.
    4. Target: The ultimate destination requested by the client (such as a Servlet, Controller, or View).

    Real-World Use Cases

    • Security & Authentication: Validating JWT tokens or session cookies before granting access to protected routes.
    • Audit Logging: Recording client IP addresses, timestamps, and request parameters across every endpoint.
    • Data Transformation: Automatically compressing response payloads with GZIP or decrypting encrypted incoming request bodies.

    Recommended Next Videos

    Continue exploring the Intercepting Filter pattern with these tutorials from our channel:


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

    Click the below Image to Enlarge

    Friday, 30 August 2013

    Intercepting Filter Design Pattern - Introduction

    🚀 Master Java Enterprise Architecture!

    Subscribe to Ram N Java for beginner-friendly design pattern tutorials, clean code architectures, and step-by-step guides!

    🔔 Subscribe to Ram N Java

    Introduction to Intercepting Filter Pattern

    In modern web and enterprise applications, incoming requests often require specialized handling before reaching their primary destination. The Intercepting Filter Design Pattern is an architectural pattern designed to intercept incoming requests and outgoing responses, applying critical pre-processing and post-processing tasks seamlessly.

    Why Do We Need This Pattern?

    When multiple services or servlets need similar administrative tasks—such as verifying security credentials, tracking user activity, or compressing payloads—hardcoding those operations into each individual handler creates heavy code duplication. The Intercepting Filter pattern solves this by:

    • Isolating Cross-Cutting Concerns: Separating logging, authentication, and encryption from business controllers.
    • Enabling Modularity: Each filter focuses exclusively on one specific operational task.
    • Declarative Chaining: Multiple filters can be combined in any designated order without altering client or target code.

    How Interception Works

    Rather than connecting directly to the destination resource, client requests flow through an interception pipeline:

    1. Pre-Processing: Filters inspect headers, authenticate tokens, decrypt incoming payloads, or audit access times.
    2. Target Delegation: If all filters pass successfully, the request reaches the target resource (such as a core servlet or controller).
    3. Post-Processing: The outgoing response can pass back through the filters to perform formatting, caching, or compression before returning to the client.

    Core Architecture Participants

    • Filter: The pluggable component performing a dedicated check or transformation.
    • Filter Chain: The manager that coordinates sequential execution across registered filters.
    • Filter Manager: Creates and configures filter chains based on the incoming request route.
    • Target: The ultimate business resource handling the client request.

    Recommended Next Videos

    Continue mastering enterprise patterns with these related tutorials from our channel:


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

    Click the below Image to Enlarge
    Intercepting Filter Design Pattern - Introduction

    Sunday, 18 August 2013

    Two Step View Design Pattern

    🚀 Master Software Architecture & Design Patterns!

    Subscribe to Ram N Java for clean, visual, and beginner-friendly programming tutorials!

    🔔 Subscribe Now

    What is the Two-Step View Design Pattern?

    The Two-Step View Pattern is an essential web presentation pattern from Martin Fowler's Patterns of Enterprise Application Architecture (PofEAA).

    Instead of transforming raw domain data directly into final HTML styling in one single pass, this pattern splits the rendering pipeline into two distinct stages:

    1. Stage 1 (Domain Data to Logical Page): Converts business objects into an unformatted, logical presentation structure (such as logical screen data or an XML model).
    2. Stage 2 (Logical Page to Target HTML): Takes the logical representation and applies the final formatting, colors, and layout for browser display.

    How the Two Stages Work

    Consider a simple example with user domain information:

    • Domain Data: A business object like Person with fields such as name: "John", age: 24, and gender: "M".
    • Stage 1 - Logical Page: The domain data is parsed into a format-agnostic logical structure (like an XML structure). At this stage, no CSS styling, screen dimensions, or final colors exist.
    • Stage 2 - Formatting & Rendering: The logical structure is rendered into actual HTML markups tailored for different output platforms—such as a desktop web layout or an optimized mobile layout.

    Key Benefits of Two-Step View

    • Centralized Global Changes: If you need to update site-wide branding, colors, or header designs, you only need to modify Stage 2 without altering how domain data is read.
    • Multi-Device Support: A single logical page produced in Stage 1 can easily feed multiple renderers (e.g., Desktop View, Mobile View, or Print/PDF format).
    • Separation of Concerns: Developers handling business models do not have to worry about front-end styling rules, keeping both layers decoupled and clean.

    Recommended Design Pattern Tutorials:


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

    Click the below Image to Enlarge
    Two Step View Design Pattern

    Two Step View Design Pattern


    See also:

  • All Design Patterns Links
  • Thursday, 15 August 2013

    Template View Design Pattern

    Master Enterprise Design Patterns!

    Subscribe to Ram N Java for clean software architecture explanations, web patterns, and enterprise Java tutorials!

    🔔 Subscribe to Ram N Java

    What is the Template View Design Pattern?

    The Template View Design Pattern is an enterprise presentation-tier design pattern (frequently referenced in Martin Fowler's Patterns of Enterprise Application Architecture). It provides a structured way to render dynamic HTML content by embedding server-side program markers or scripts directly within static visual templates.

    Rather than writing code that generates entire HTML documents using string concatenations or print statements, developers write standard HTML pages and insert specialized placeholders or script tags where dynamic model data should be rendered.

    How the Template View Pattern Works

    The main philosophy behind Template View is separation of visual presentation from complex business logic:

    • Static Page Framework: Designers create standard HTML layout pages (headers, navigation bars, CSS styling, and footers) using regular web tools.
    • Dynamic Placeholders: Specific tags or expressions (such as JSP expressions, Thymeleaf tags, or ASP tags) pull data passed from the controller or model.
    • Server-Side Processing: During request execution, the template engine processes the page, replaces markers with real database or business object values, and returns standard HTML to the browser.

    Key Benefits & Real-World Implementations

    Common implementations of this pattern include JavaServer Pages (JSP), Thymeleaf, FreeMarker, and Velocity. Major advantages include:

    • Improved Maintainability: UI layout changes do not require altering or recompiling core backend business logic.
    • Collaboration Friendly: UI/UX designers can work directly with the template files without deep knowledge of server-side application logic.
    • Cleaner Presentation Code: Eliminates messy Java code responsible for outputting raw HTML tags.

    Related Tutorials from Ram N Java


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

    Click the below Image to Enlarge
    Template View Design Pattern















    See also:

  • All Design Patterns Links
  • Transform View Design Pattern

    🚀 Boost Your Software Design Skills!

    Subscribe to Ram N Java for simple, clear, and beginner-friendly programming tutorials!

    🔔 Subscribe Now

    What is the Transform View Design Pattern?

    When building modern web applications, presenting domain data clearly to users is critical. The Transform View Design Pattern is a foundational web presentation pattern from Martin Fowler’s Patterns of Enterprise Application Architecture (PofEAA).

    In simple terms: A Transform View processes domain data element-by-element and transforms it into HTML formatting for browser display.

    The Core Components Explained

    The pattern works around three essential building blocks:

    • Model (Domain Data): Contains the actual business data and objects without any presentation logic. For example:
      • Album: Contains attributes like album name and album title.
      • Artist: Contains attributes like artist name, age, and gender.
    • Transformer: Reads the raw domain data element by element, applies transformation rules, and converts that data directly into an HTML layout.
    • HTML View: The generated HTML page rendered in the web browser for the end user to see.

    Why Use Transform View?

    • Clean Separation: Your business models remain pure and unaware of how they are rendered on screen.
    • Multiple Outputs: A transformer can turn the exact same domain data into HTML, XML, or PDF without touching the underlying domain logic.
    • Simplicity: It provides a structured, predictable pipeline for converting structured data into visual markup.

    Recommended Design Pattern Tutorials:


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

    Click the below Image to Enlarge
    Transform View Design Pattern














    See also:

  • All Design Patterns Links
  • Tutorials