Class StaticFileHandler
This class extends MethodeBasedHandler and provides implementations for handling
HTTP GET and HEAD requests to serve static files. It supports:
- Serving files from a configurable root directory
- Automatic MIME type detection based on file extensions
- Default serving of index.html for directory requests
- HEAD requests for retrieving file metadata without body content
Security considerations:
- All file paths are resolved relative to the configured root directory
- Directory traversal is prevented by the Path resolution mechanism
- Only existing files can be served; directories without index.html return 404
Example usage:
StaticFileHandler handler = new StaticFileHandler("/var/www/html");
// Requests to /styles.css will serve /var/www/html/styles.css
// Requests to / will serve /var/www/html/index.html
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionStaticFileHandler(String rootPath) Constructs a StaticFileHandler with the specified root directory. -
Method Summary
Modifier and TypeMethodDescriptionprotected HTTPResponsehandleGetRequest(HTTPRequest request) Handles HTTP GET requests by serving static files from the root directory.protected HTTPResponsehandleHeadRequest(HTTPRequest request) Handles HTTP HEAD requests by returning file metadata without the file contents.Methods inherited from class MethodeBasedHandler
handle, handleDeleteRequest, handlePostRequest, handlePutRequestMethods inherited from class RequestHandler
handle
-
Constructor Details
-
StaticFileHandler
Constructs a StaticFileHandler with the specified root directory.The root directory serves as the base path for all file serving operations. File requests will be resolved relative to this directory, providing isolation and preventing access to files outside the designated static content area.
Example:
// Serve files from /var/www/html StaticFileHandler handler = new StaticFileHandler("/var/www/html"); // Request to /images/logo.png will resolve to /var/www/html/images/logo.png- Parameters:
rootPath- The absolute or relative root directory path from which files will be served. Should be a valid directory path on the file system.
-
-
Method Details
-
handleGetRequest
Handles HTTP GET requests by serving static files from the root directory.This method implements the following logic:
- Resolves the requested path relative to the root directory
- If the path is a directory, attempts to serve "index.html" from that directory
- Validates that the resolved path exists and is a file (not a directory)
- Reads the file contents into memory
- Detects the MIME type automatically or defaults to "application/octet-stream"
- Returns an HTTP 200 response with the file contents and appropriate Content-Type
Directory handling:
- Request to
/→ serves/index.html - Request to
/docs/→ serves/docs/index.html - If index.html doesn't exist, throws
NotFoundException
MIME type detection is performed using
Files.probeContentType(Path), which uses the file extension to determine the content type (e.g., .html → text/html, .css → text/css, .js → application/javascript).- Overrides:
handleGetRequestin classMethodeBasedHandler- Parameters:
request- The HTTP GET request containing the path of the file to serve.- Returns:
- An HTTPResponse with status 200 containing the file contents and appropriate headers.
- Throws:
NotFoundException- If the file is not found, is a directory without index.html, or the path is invalid.InternalServerErrorException- If an I/O error occurs while reading the file (e.g., permission denied, disk error).Exception- If any other unexpected error occurs during request handling.
-
handleHeadRequest
Handles HTTP HEAD requests by returning file metadata without the file contents.The HTTP HEAD method is identical to GET except that the server MUST NOT return a message body in the response. This method is commonly used to:
- Check if a file exists without downloading it
- Retrieve file metadata (size, content type) for caching decisions
- Verify links without transferring large amounts of data
This method implements the following logic:
- Resolves the requested path relative to the root directory
- If the path is a directory, attempts to check for "index.html" in that directory
- Validates that the resolved path exists and is a file (not a directory)
- Retrieves file size using
Files.size(Path) - Detects the MIME type automatically or defaults to "application/octet-stream"
- Returns an HTTP 200 response with Content-Length and Content-Type headers, but NO body
The returned response includes the same headers that would be sent in a GET request, allowing clients to make decisions about whether to fetch the full resource.
- Overrides:
handleHeadRequestin classMethodeBasedHandler- Parameters:
request- The HTTP HEAD request containing the path of the file to check.- Returns:
- An HTTPResponse with status 200 containing only headers (Content-Length, Content-Type), without any message body.
- Throws:
NotFoundException- If the file is not found, is a directory without index.html, or the path is invalid.InternalServerErrorException- If an I/O error occurs while accessing file metadata (e.g., permission denied, disk error).Exception- If any other unexpected error occurs during request handling.
-