# Javax / Faces

## Overview

The `javax.faces` package is the root-level entry point for the JavaServer Faces (JSF) framework — a component-based web application framework built on top of the Java Servlet API. It provides the full server-side MVC (Model-View-Controller) stack for building Java web applications, replacing raw servlet and JSP manipulation with a structured lifecycle, event model, and component tree.

JSF treats a web page as a tree of server-side components. When a user interacts with a page, the request flows through a well-defined six-phase lifecycle that restores the component state, processes form input, validates data, updates backing beans, executes action methods, and renders the resulting HTML response. The framework is entirely built into the `javax` namespace as part of the Java EE (now Jakarta EE) platform.

This package encompasses the core runtime classes — `FacesContext`, `UIViewRoot`, `UIComponent`, converters, validators, listeners, and lifecycle infrastructure — as well as the web-facing servlet layer that bridges the servlet container with the JSF component model.

## Sub-module Guide

The `javax.faces` area splits into a single primary sub-module:

### `javax.faces.webapp` — The Web Entry Point

The `webapp` subpackage is the gateway between the servlet container and the JSF framework. Its star class is `FacesServlet`, which implements the **Front Controller** pattern: a single servlet that intercepts all JSF-managed requests and routes them through the six-phase JSF lifecycle.

`FacesServlet` handles both GET and POST requests:
- **GET** requests typically trigger an initial page render (Restore View → Render Response, skipping validation and model update).
- **POST** requests (form submissions, action callbacks) traverse the full lifecycle, processing user input and invoking application logic.

The servlet is configured via `web-full.xml` in the web deployment descriptor, where its URL pattern (commonly `*.jsf`, `*.faces`, or `/faces/*`) determines which requests are processed by JSF and which pass through to static resources.

**How the sub-module fits:** The `webapp` subpackage is the *only* child module under `javax.faces` from a structural standpoint. It is the bridge layer — everything else in `javax.faces` lives in other subpackages (`javax.faces.component`, `javax.faces.context`, `javax.faces.lifecycle`, `javax.faces.convert`, `javax.faces.validator`, etc.) that `webapp` depends on. There are no sibling sub-modules at this level; `webapp` is the top-level child.

## Key Patterns and Architecture

### The Six-Phase Lifecycle

At the heart of JSF is a fixed, six-phase request lifecycle. Every HTTP request mapped to `FacesServlet` goes through these phases in order:

```mermaid
flowchart TD
    phase1["1. Restore View<br/>Rebuild component tree from state"] --> phase2["2. Apply Request Values<br/>Populate components from request params"]
    phase2 --> phase3["3. Process Validations<br/>Convert, validate, report errors"]
    phase3 --> phase4["4. Update Model Values<br/>Transfer valid data to backing beans"]
    phase4 --> phase5["5. Invoke Application<br/>Execute action methods and navigation"]
    phase5 --> phase6["6. Render Response<br/>Build HTML output from component tree"]
```

If validation fails at phase 3, the flow short-circuits directly to phase 6 (Render Response) with error messages displayed.

### Front Controller Pattern

`FacesServlet` is a classic Front Controller. All JSF requests pass through this single entry point, which:

- Classifies each request as a POST or GET and dispatches accordingly.
- Creates or retrieves a `FacesContext` instance for the current request.
- Invokes the framework lifecycle phases sequentially.
- Ensures consistent error handling, cross-cutting concerns, and state management across every request.

### Server-Side Component State

JSF preserves the entire UI component tree server-side between requests. This is achieved through:

- **View State** — the component tree is serialized and stored either in the HTTP session or as a hidden form field (via the `StateHelper`).
- **UIViewRoot** — the root node of the component tree for a given view, recreated in each request's Restore View phase from the stored state.
- **FacesContext** — a per-request context that holds the component tree, flash scope, message list, and external request/response objects.

This server-side approach enables rich UI interactions without requiring the client to understand page structure, at the cost of increased server memory usage for large component trees.

### Extensibility Hooks

JSF provides multiple extension points so developers can customize behavior without modifying framework code:

| Hook | Purpose |
|------|---------|
| `PhaseListener` | Execute custom logic before or after any lifecycle phase. |
| `ViewHandler` | Customize how views are created, rendered, and navigated. |
| `FacesConverter` | Define custom type conversion (e.g., string-to-object). |
| `FacesValidator` | Apply custom validation rules to components. |
| `Lifecycle` | Implement a custom lifecycle (rare; most customization uses PhaseListener). |
| `FacesListener` (Component) | React to component events (add, remove, value change). |

For cross-cutting concerns like authentication or logging, a Servlet Filter is typically preferred over extending `FacesServlet`.

### Configuration Model

JSF behavior is controlled through initialization parameters in the web deployment descriptor:

| Parameter | Purpose |
|-----------|---------|
| `javax.faces.DEFAULT_SUFFIX` | Default view file extension (e.g., `.xhtml` for Facelets). |
| `javax.faces.PROJECT_STAGE` | Runtime stage (`Development`, `Production`, `System`, `UnitTest`). |
| `javax.faces.FACELETS_REFRESH_PERIOD` | Facelets template reload interval during development. |

Project stage (`Development` vs `Production`) controls debug output, EL validation strictness, and template compilation caching — a critical distinction for production deployments.

## Dependencies and Integration

### Internal Dependencies

The `javax.faces.webapp` subpackage sits at the top of the dependency hierarchy within `javax.faces`. It depends on core JSF runtime classes defined in sibling subpackages (not captured in the index at this level):

- `javax.faces.context` — `FacesContext`, `ExternalContext`, `UIViewRoot`.
- `javax.faces.lifecycle` — `Lifecycle`, `PhaseId`, `PhaseListener`.
- `javax.faces.component` — `UIComponent`, `UIData`, `UIInput`, `UIOutput`, `UIViewRoot`.
- `javax.faces.convert` — Built-in type converters.
- `javax.faces.validator` — Built-in validators.
- `javax.faces.application` — Application-level services, navigation handler, resource handler.

### External Dependencies

| External System | Integration Method |
|----------------|-------------------|
| Servlet Container | `javax.servlet.Servlet` API; integrates with Tomcat, Jetty, WebLogic, etc. |
| Facelets | `.xhtml` view technology; the modern JSF 2.x+ default view handler. |
| JSP (legacy) | `.jsp` views; supported in older JSF 1.x applications. |
| CDI / Managed Beans | `javax.enterprise.context` (CDI, JSF 2.x+) or JSF's built-in managed-bean mechanism (JSF 1.x) provides backing objects. |
| EL (Expression Language) | `javax.el` resolves `${bean.property}` expressions in view templates. |

### Component Interaction

The following diagram shows how the key components interact during a request:

```mermaid
flowchart TD
    subgraph External["External"]
        client["Browser / Client"]
    end
    subgraph Servlet["javax.faces.webapp"]
        servlet["FacesServlet"]
        lifecycle["JSF Lifecycle"]
        stateMgmt["View State Mgmt"]
    end
    subgraph Core["javax.faces Core"]
        ctx["FacesContext"]
        viewRoot["UIViewRoot"]
        components["UIComponent Tree"]
        managedBeans["Managed Bean"]
    end
    subgraph Config["Configuration"]
        webXml["web-full.xml"]
        initParams["Init Parameters"]
    end
    client -->|"HTTP Request"| servlet
    servlet -->|invokes| lifecycle
    lifecycle -->|Restore View| viewRoot
    viewRoot -->|holds| components
    lifecycle -->|Apply Request Values| ctx
    lifecycle -->|Process Validations| ctx
    lifecycle -->|Update Model| managedBeans
    lifecycle -->|Invoke Application| managedBeans
    lifecycle -->|Render Response| components
    components -->|encodeEnd| html["HTML Output"]
    html --> client
    servlet -->|stores state| stateMgmt
    stateMgmt -->|restores| viewRoot
    servlet -->|reads config from| webXml
    webXml --> initParams
```

## Notes for Developers

### Thread Safety

`FacesServlet` is inherently thread-safe. 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 vs. Using Hooks

In most cases, you should **not** extend `FacesServlet` directly. Instead:

- Use **`PhaseListener`** for pre/post lifecycle phase hooks.
- Use a **Servlet Filter** for cross-cutting concerns (authentication, logging, GZIP compression).
- Use **`ViewHandler`** overrides to customize view creation/rendering.
- Use **`FacesConverter`** / **`FacesValidator`** for type-specific logic.

### Project Stages in Practice

- **`Development`** — Disable facelets compilation caching, enable strict EL validation, provide debug output. Use locally for rapid iteration.
- **`Production`** — Enable all optimizations, disable debug output. This is the default deployment stage.
- **`System`** / **`UnitTest`** — Intermediate stages for integration testing or system-level validation.

### Troubleshooting

| Symptom | Likely Cause |
|---------|-------------|
| 404 on JSF pages | Servlet mapping in `web-full.xml` does not match the request URL pattern. |
| Missing component tree state | Session storage limits exceeded; check session configuration for large component trees. |
| EL expressions not resolving | Verify `javax.faces.DEFAULT_SUFFIX` is set correctly and the Facelets/JSP library is on the classpath. |
| Duplicate form submission issues | Ensure proper use of the POST-Redirect-GET pattern in action methods. |

### View Technology Choice

- **Facelets (`.xhtml`)** is the modern, recommended view technology for JSF 2.x and later. It offers template composition, tag libraries, and faster compilation than JSP.
- **JSP (`.jsp`)** is legacy and primarily seen in JSF 1.x applications. It has slower compilation and limited template support.

### State Management Considerations

For large-scale deployments, the default server-side view state stored in the HTTP session can become a memory bottleneck. Options include:

- **Client-side state** — Store view state in a hidden form field instead of the session (via `javax.faces.STATE_SAVING_METHOD=context`). This shifts memory to the client but increases page size.
- **Stateless views** — Use `UIViewRoot` without state saving for pages with no form input or AJAX updates.
- **Session replication** — In clustered environments, ensure HTTP sessions (and their stored view state) are properly replicated across nodes.
