# Javax / Faces / Webapp

## Overview

The `javax.faces.webapp` subpackage provides the web-facing entry point for JavaServer Faces (JSF) applications. Its primary responsibility is the `FacesServlet`, which acts as the central dispatcher for all JSF requests — routing incoming HTTP requests through the JSF lifecycle, managing view creation and rendering, and bridging the servlet container with the JSF component model. This module is the gateway that turns the servlet container into a JSF-powered web application.

## Key Classes

### FacesServlet

[`FacesServlet.java`](full-fixture-codebase/src/java/javax/faces/webapp/FacesServlet.java) — `public class FacesServlet`

The `FacesServlet` is the heart of the JSF web tier. It is a standard `javax.servlet.Servlet` that handles all requests mapped to its URL pattern (by convention, `*.jsf`, `*.faces`, or `/faces/*`).

**Purpose and role.** Every request that the JSF framework needs to process flows through this servlet. It is responsible for:

- Detecting whether the incoming request is a **POST** (a form submission that should advance through the full JSF lifecycle) or a **GET** (a page render request).
- Invoking the **JSF lifecycle** phases: Restore View, Apply Request Values, Process Validations, Update Model Values, Invoke Application, and Render Response.
- Managing **view state** — storing and retrieving the component tree state between requests so that form data and UI component state survive the stateless HTTP protocol.
- Creating and caching **view references** (`UIViewRoot` instances) that represent the server-side component tree for a given page.
- Delegating to **resource loaders** and **naming contexts** to resolve view templates (e.g., JSP or Facelets pages) and render them with data bound to managed beans.

**Design role.** The `FacesServlet` follows the **Front Controller** pattern — a single entry point that orchestrates the entire request-processing flow for the JSF framework. This keeps request handling consistent and allows the framework to apply cross-cutting concerns (lifecycle management, state handling, error processing) uniformly to every request.

**Configuration.** The servlet is registered in the web application's deployment descriptor. The evidence shows `web-full.xml` references `FacesServlet`, indicating the standard JSF web configuration that declares the servlet and maps it to URL patterns. Engineers working on this module should consult `web-full.xml` to understand the servlet mapping and initialization parameters.

**Key configuration points** (convention-based, inferred from standard JSF behavior):
- `javax.faces.DEFAULT_SUFFIX` — the default file extension for view pages (e.g., `.xhtml` for Facelets, `.jsp` for older JSP-based views).
- `javax.faces.PROJECT_STAGE` — the application's project stage (`Development`, `Production`, etc.) that controls behavior such as debug output and validation strictness.
- `javax.faces.FACELETS_REFRESH_PERIOD` — how often Facelets templates are reloaded during development.

## How It Works

### Typical Request Flow

```
                    ┌─────────────────────────────────┐
                    │         Browser / Client         │
                    └──────────────┬──────────────────┘
                                   │ HTTP Request
                                   ▼
              ┌──────────────────────────────────────────┐
              │            FacesServlet (webapp)         │
              │  1. Receive request (doGet / doPost)     │
              │  2. Determine request type (POST vs GET) │
              │  3. Invoke JSF Lifecycle                 │
              │  4. Render response (HTML)               │
              └──────────────┬───────────────────────────┘
                             │ HTML Response
                             ▼
                      ┌────────────────┐
                      │    Browser     │
                      └────────────────┘
```

### Step-by-step request processing

A typical request flows through the following stages:

1. **Request reception.** The servlet container dispatches the HTTP request to `FacesServlet` based on the URL pattern defined in `web-full.xml`.

2. **Request classification.** The servlet determines whether this is a **POST** (form submission or action callback) or a **GET** (initial page load or AJAX update). This distinction is critical because POST requests traverse the full lifecycle while GET requests typically skip validation and model update phases.

3. **Lifecycle invocation.** The servlet delegates to the `FacesServletLifecycle` (a framework-internal class) to execute the JSF lifecycle for the request. The lifecycle proceeds through six phases:

   ```
   Flowchart of JSF Lifecycle Phases
   ┌─────────────────────────┐
   │  1. Restore View        │  ← Rebuild component tree from view state
   └──────────┬──────────────┘
              ▼
   ┌─────────────────────────┐
   │  2. Apply Request       │  ← Read submitted values from request
   │     Values              │    parameters and populate UI components
   └──────────┬──────────────┘
              ▼
   ┌─────────────────────────┐
   │  3. Process Validations │  ← Convert, validate, and display errors
   └──────────┬──────────────┘
              ▼
   ┌─────────────────────────┐
   │  4. Update Model        │  ← Transfer validated values to backing
   │     Values              │    beans (managed beans)
   └──────────┬──────────────┘
              ▼
   ┌─────────────────────────┐
   │  5. Invoke Application  │  ← Execute action methods, navigation
   └──────────┬──────────────┘
              ▼
   ┌─────────────────────────┐
   │  6. Render Response     │  ← Build HTML output from component tree
   └─────────────────────────┘
   ```

4. **View rendering.** In the Render Response phase, the servlet iterates the component tree, calling each component's `encodeEnd()` method to produce HTML output. The result is written to the `HttpServletResponse` and returned to the client.

5. **View state management.** Between requests, the server-side component tree is serialized and stored (typically in the HTTP session or as a hidden form field via the `StateHelper`). On the next request, it is deserialized in the Restore View phase.

### Architectural decisions

- **Front Controller pattern.** All JSF requests pass through a single servlet, ensuring consistent lifecycle execution and centralized control over view rendering.
- **Server-side state.** The component tree is preserved server-side between requests, enabling rich client interactions without the client needing to understand the page structure.
- **Servlet-based.** As a `javax.servlet.Servlet`, `FacesServlet` integrates directly with the Java EE web container, benefiting from the container's thread safety, connection pooling, and deployment model.

## Data Model

The `FacesServlet` does not define its own persistent data model. Instead, it operates on transient in-memory structures:

- **`UIViewRoot`** — the root of the JSF component tree for a given view. Represents an entire page.
- **`UIComponent`** hierarchy — the tree of server-side UI components (buttons, text fields, panels, etc.) that correspond to elements in the rendered HTML.
- **`FacesContext`** — the per-request context object that holds request-scoped information including the component tree, flash scope, messages, and the external request/response objects.
- **Managed Beans** — POJOs backed by JSF managed-bean configurations (XML or annotations) that serve as data sources for the view.

These structures are not defined within `javax.faces.webapp` itself; they live in the broader `javax.faces` runtime. The servlet's job is to create, manage, and destroy them in response to the request flow.

## Dependencies and Integration

### Inbound dependencies

| Consumer | Relationship |
|----------|-------------|
| `web-full.xml` | Declares the `FacesServlet` servlet and maps it to URL patterns in the web deployment descriptor. |

### Outbound dependencies (framework-level, inferred)

The `FacesServlet` depends on core JSF framework classes defined elsewhere in the `javax.faces` runtime:

```mermaid
flowchart LR
    client["Browser / Client"] -->|"HTTP Request"| servlet["FacesServlet"]
    servlet -->|invokes| lifecycle["JSF Lifecycle"]
    lifecycle -->|"restores| renders"| view["UIViewRoot / UIComponent Tree"]
    lifecycle -->|"binds to"| bean["Managed Bean"]
    lifecycle -->|"uses"| ctx["FacesContext"]
    servlet -->|"config from"| webxml["web-full.xml"]
    servlet -->|"returns| renders"| response["HTML Response"]
    response --> client
```

### Integration points

- **Servlet container** — Tomcat, Jetty, WebLogic, etc. The servlet integrates via the `javax.servlet` API.
- **JSF lifecycle runtime** — the framework-internal classes that implement each lifecycle phase.
- **View technology** — Facelets (`.xhtml`) is the modern default; older JSF 1.x applications may use JSP (`.jsp`) views.
- **Managed Bean container** — CDI (JSF 2.x+) or JSF's built-in managed-bean mechanism (JSF 1.x) provides the backing objects that the servlet binds data to.

## Notes for Developers

### Servlet mapping

The URL pattern that maps to `FacesServlet` determines which requests the JSF lifecycle processes. Common conventions:

- `*.jsf` or `*.faces` — all requests with these extensions go through JSF. Static resources (`.css`, `.js`, `.png`) are excluded by default.
- `/faces/*` — path-based mapping where any URL starting with `/faces/` is handled by JSF.

### Thread safety

`FacesServlet` is thread-safe by design. The servlet container creates a single instance that handles all requests concurrently. Each request gets its own `FacesContext` instance, so there is no shared mutable state between threads at the request level.

### Extending FacesServlet

In most cases, you do not need to extend `FacesServlet`. If you do need custom request processing, consider:

- **`PhaseListener`** — attach custom logic before or after any lifecycle phase.
- **`ViewHandler`** — customize how views are created and rendered.
- **`FacesConverter`** / **`FacesValidator`** — customize conversion and validation for specific data types.
- **Servlet Filter** — apply cross-cutting logic (authentication, logging, compression) around the servlet without extending it.

### Project stages

The `javax.faces.PROJECT_STAGE` initialization parameter controls runtime behavior:

- `Development` — enables debug output, disables facelets compilation caching, enables strict EL validation.
- `Production` — disables debug output, enables all optimizations.
- `System` / `UnitTest` — intermediate stages for specific deployment scenarios.

### Troubleshooting

- **404 on JSF pages** — verify the servlet mapping in `web-full.xml` matches the request URL.
- **Missing component tree state** — check session configuration; large component trees may exceed session storage limits.
- **EL expressions not resolving** — verify the `javax.faces.DEFAULT_SUFFIX` and that the Facelets/JSP library is on the classpath.
