- FileServlet

Available since OmniFaces 2.2

The well known "BalusC FileServlet", as an abstract template, slightly refactored, rewritten and modernized with a.o. fast NIO stuff instead of legacy RandomAccessFile. GZIP support is stripped off as that can be done application wide via GzipResponseFilter.

This servlet properly deals with ETag, If-None-Match and If-Modified-Since caching requests, hereby improving browser caching. This servlet also properly deals with Range and If-Range ranging requests (RFC 7233), which is required by most media players for proper audio/video streaming, and by webbrowsers and for a proper resume of an paused download, and by download accelerators to be able to request smaller parts simultaneously. This servlet is ideal when you have large files like media files placed outside the web application and you can't use the default servlet.


Just extend this class and override the getFile(HttpServletRequest) method to return the desired file. If you want to trigger a HTTP 400 "Bad Request" error, simply throw IllegalArgumentException. If you want to trigger a HTTP 404 "Not Found" error, simply return null, or a non-existent file.

Here's a concrete example which serves it via an URL like /media/foo.ext:

public class MediaFileServlet extends FileServlet {

    private File folder;

    public void init() throws ServletException {
        folder = new File("/var/webapp/media");

    protected File getFile(HttpServletRequest request) {
        String pathInfo = request.getPathInfo();

        if (pathInfo == null || pathInfo.isEmpty() || "/".equals(pathInfo)) {
            throw new IllegalArgumentException();

        return new File(folder, pathInfo);


You can embed it in e.g. HTML5 video tag as below:

<video src="#{request.contextPath}/media/video.mp4" controls="controls" />

Customizing FileServlet

If more fine grained control is desired for handling "file not found" error, determining the cache expire time, the content type, whether the file should be supplied as an attachment and the attachment's file name, then the developer can opt to override one or more of the following protected methods:

See also:

Documentation & Sources