Class FileServlet

  • All Implemented Interfaces:
    Servlet, ServletConfig, Serializable

    public abstract class FileServlet
    extends HttpServlet

    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 CompressedResponseFilter.

    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.

    Usage

    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:

     @WebServlet("/media/*")
     public class MediaFileServlet extends FileServlet {
    
         private File folder;
    
         @Override
         public void init() throws ServletException {
             folder = new File("/var/webapp/media");
         }
    
         @Override
         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:

    Since:
    2.2
    Author:
    Bauke Scholtz
    See Also:
    Serialized Form
    • Constructor Detail

      • FileServlet

        public FileServlet()
    • Method Detail

      • handleFileNotFound

        protected void handleFileNotFound​(HttpServletRequest request,
                                          HttpServletResponse response)
                                   throws IOException
        Handles the case when the file is not found.

        The default implementation sends a HTTP 404 error.

        Parameters:
        request - The involved HTTP servlet request.
        response - The involved HTTP servlet response.
        Throws:
        IOException - When something fails at I/O level.
        Since:
        2.3
      • getExpireTime

        protected long getExpireTime​(HttpServletRequest request,
                                     File file)
        Returns how long the resource may be cached by the client before it expires, in seconds.

        The default implementation returns 30 days in seconds.

        Parameters:
        request - The involved HTTP servlet request.
        file - The involved file.
        Returns:
        The client cache expire time in seconds (not milliseconds!).
      • getContentType

        protected String getContentType​(HttpServletRequest request,
                                        File file)
        Returns the content type associated with the given HTTP servlet request and file.

        The default implementation delegates File.getName() to ServletContext.getMimeType(String) with a fallback default value of application/octet-stream.

        Parameters:
        request - The involved HTTP servlet request.
        file - The involved file.
        Returns:
        The content type associated with the given HTTP servlet request and file.
      • isAttachment

        protected boolean isAttachment​(HttpServletRequest request,
                                       String contentType)
        Returns true if we must force a "Save As" dialog based on the given HTTP servlet request and content type as obtained from getContentType(HttpServletRequest, File).

        The default implementation will return true if the content type does not start with text or image, and the Accept request header is either null or does not match the given content type.

        Parameters:
        request - The involved HTTP servlet request.
        contentType - The content type of the involved file.
        Returns:
        true if we must force a "Save As" dialog based on the given HTTP servlet request and content type.
      • getAttachmentName

        protected String getAttachmentName​(HttpServletRequest request,
                                           File file)
        Returns the file name to be used in Content-Disposition header. This does not need to be URL-encoded as this will be taken care of.

        The default implementation returns File.getName().

        Parameters:
        request - The involved HTTP servlet request.
        file - The involved file.
        Returns:
        The file name to be used in Content-Disposition header.
        Since:
        2.3