Class DefaultServlet

  • All Implemented Interfaces:
    Servlet, ServletConfig, java.io.Serializable
    Direct Known Subclasses:
    WebdavServlet

    public class DefaultServlet
    extends HttpServlet

    The default resource-serving servlet for most web applications, used to serve static resources such as HTML pages and images.

    This servlet is intended to be mapped to / e.g.:

       <servlet-mapping>
           <servlet-name>default</servlet-name>
           <url-pattern>/</url-pattern>
       </servlet-mapping>
     

    It can be mapped to sub-paths, however in all cases resources are served from the web application resource root using the full path from the root of the web application context.
    e.g. given a web application structure:

     /context
       /images
         tomcat2.jpg
       /static
         /images
           tomcat.jpg
     

    ... and a servlet mapping that maps only /static/* to the default servlet:

       <servlet-mapping>
           <servlet-name>default</servlet-name>
           <url-pattern>/static/*</url-pattern>
       </servlet-mapping>
     

    Then a request to /context/static/images/tomcat.jpg will succeed while a request to /context/images/tomcat2.jpg will fail.

    Author:
    Craig R. McClanahan, Remy Maucherat
    See Also:
    Serialized Form
    • Field Detail

      • sm

        protected static final StringManager sm
        The string manager for this package.
      • FULL

        protected static final Ranges FULL
        Full range marker.
      • mimeSeparation

        protected static final java.lang.String mimeSeparation
        MIME multipart separation string
        See Also:
        Constant Field Values
      • BUFFER_SIZE

        protected static final int BUFFER_SIZE
        Size of file transfer buffer in bytes.
        See Also:
        Constant Field Values
      • debug

        protected int debug
        The debugging detail level for this servlet.
      • input

        protected int input
        The input buffer size to use when serving resources.
      • listings

        protected boolean listings
        Should we generate directory listings?
      • readOnly

        protected boolean readOnly
        Read only flag. By default, it's set to true.
      • output

        protected int output
        The output buffer size to use when serving resources.
      • localXsltFile

        protected java.lang.String localXsltFile
        Allow customized directory listing per directory.
      • contextXsltFile

        protected java.lang.String contextXsltFile
        Allow customized directory listing per context.
      • globalXsltFile

        protected java.lang.String globalXsltFile
        Allow customized directory listing per instance.
      • readmeFile

        protected java.lang.String readmeFile
        Allow a readme file to be included.
      • resources

        protected transient WebResourceRoot resources
        The complete set of web application resources
      • fileEncoding

        protected java.lang.String fileEncoding
        File encoding to be used when reading static files. If none is specified the platform default is used.
      • sendfileSize

        protected int sendfileSize
        Minimum size for sendfile usage in bytes.
      • useAcceptRanges

        protected boolean useAcceptRanges
        Should the Accept-Ranges: bytes header be send with static resources?
      • showServerInfo

        protected boolean showServerInfo
        Flag to determine if server information is presented.
      • sortListings

        protected boolean sortListings
        Flag to determine if resources should be sorted.
      • sortManager

        protected transient org.apache.catalina.servlets.DefaultServlet.SortManager sortManager
        The sorting manager for sorting files and directories.
    • Constructor Detail

      • DefaultServlet

        public DefaultServlet()
    • Method Detail

      • getRelativePath

        protected java.lang.String getRelativePath​(HttpServletRequest request)
        Return the relative path associated with this servlet.
        Parameters:
        request - The servlet request we are processing
        Returns:
        the relative path
      • getRelativePath

        protected java.lang.String getRelativePath​(HttpServletRequest request,
                                                   boolean allowEmptyPath)
      • getPathPrefix

        protected java.lang.String getPathPrefix​(HttpServletRequest request)
        Determines the appropriate path to prepend resources with when generating directory listings. Depending on the behaviour of getRelativePath(HttpServletRequest) this will change.
        Parameters:
        request - the request to determine the path for
        Returns:
        the prefix to apply to all resources in the listing.
      • doGet

        protected void doGet​(HttpServletRequest request,
                             HttpServletResponse response)
                      throws java.io.IOException,
                             ServletException
        Description copied from class: jakarta.servlet.http.HttpServlet
        Called by the server (via the service method) to allow a servlet to handle a GET request.

        Overriding this method to support a GET request also automatically supports an HTTP HEAD request. A HEAD request is a GET request that returns no body in the response, only the request header fields.

        When overriding this method, read the request data, write the response headers, get the response's Writer or output stream object, and finally, write the response data. It's best to include content type and encoding. When using a PrintWriter object to return the response, set the content type before accessing the PrintWriter object.

        The servlet container must write the headers before committing the response, because in HTTP the headers must be sent before the response body.

        Where possible, set the Content-Length header (with the ServletResponse.setContentLength(int) method), to allow the servlet container to use a persistent connection to return its response to the client, improving performance. The content length is automatically set if the entire response fits inside the response buffer.

        When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set the Content-Length header.

        The GET method should be safe, that is, without any side effects for which users are held responsible. For example, most form queries have no side effects. If a client request is intended to change stored data, the request should use some other HTTP method.

        The GET method should also be idempotent, meaning that it can be safely repeated. Sometimes making a method safe also makes it idempotent. For example, repeating queries is both safe and idempotent, but buying a product online or modifying data is neither safe nor idempotent.

        If the request is incorrectly formatted, doGet returns an HTTP "Bad Request" message.

        Overrides:
        doGet in class HttpServlet
        Parameters:
        request - an HttpServletRequest object that contains the request the client has made of the servlet
        response - an HttpServletResponse object that contains the response the servlet sends to the client
        Throws:
        java.io.IOException - if an input or output error is detected when the servlet handles the GET request
        ServletException - if the request for the GET could not be handled
        See Also:
        ServletResponse.setContentType(java.lang.String)
      • doHead

        protected void doHead​(HttpServletRequest request,
                              HttpServletResponse response)
                       throws java.io.IOException,
                              ServletException
        Description copied from class: jakarta.servlet.http.HttpServlet

        Receives an HTTP HEAD request from the protected service method and handles the request. The client sends a HEAD request when it wants to see only the headers of a response, such as Content-Type or Content-Length. The HTTP HEAD method counts the output bytes in the response to set the Content-Length header accurately.

        If you override this method, you can avoid computing the response body and just set the response headers directly to improve performance. Make sure that the doHead method you write is both safe and idempotent (that is, protects itself from being called multiple times for one HTTP HEAD request).

        If the HTTP HEAD request is incorrectly formatted, doHead returns an HTTP "Bad Request" message.

        Overrides:
        doHead in class HttpServlet
        Parameters:
        request - the request object that is passed to the servlet
        response - the response object that the servlet uses to return the headers to the client
        Throws:
        java.io.IOException - if an input or output error occurs
        ServletException - if the request for the HEAD could not be handled
      • doOptions

        protected void doOptions​(HttpServletRequest req,
                                 HttpServletResponse resp)
                          throws ServletException,
                                 java.io.IOException
        Override default implementation to ensure that TRACE is correctly handled.
        Overrides:
        doOptions in class HttpServlet
        Parameters:
        req - the HttpServletRequest object that contains the request the client made of the servlet
        resp - the HttpServletResponse object that contains the response the servlet returns to the client
        Throws:
        java.io.IOException - if an input or output error occurs while the servlet is handling the OPTIONS request
        ServletException - if the request for the OPTIONS cannot be handled
      • determineMethodsAllowed

        protected java.lang.String determineMethodsAllowed​(HttpServletRequest req)
        Determines the methods normally allowed for the resource.
        Parameters:
        req - The Servlet request
        Returns:
        The allowed HTTP methods
      • doPost

        protected void doPost​(HttpServletRequest request,
                              HttpServletResponse response)
                       throws java.io.IOException,
                              ServletException
        Description copied from class: jakarta.servlet.http.HttpServlet
        Called by the server (via the service method) to allow a servlet to handle a POST request. The HTTP POST method allows the client to send data of unlimited length to the Web server a single time and is useful when posting information such as credit card numbers.

        When overriding this method, read the request data, write the response headers, get the response's Writer or output stream object, and finally, write the response data. It's best to include content type and encoding. When using a PrintWriter object to return the response, set the content type before accessing the PrintWriter object.

        The servlet container must write the headers before committing the response, because in HTTP the headers must be sent before the response body.

        Where possible, set the Content-Length header (with the ServletResponse.setContentLength(int) method), to allow the servlet container to use a persistent connection to return its response to the client, improving performance. The content length is automatically set if the entire response fits inside the response buffer.

        When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set the Content-Length header.

        This method does not need to be either safe or idempotent. Operations requested through POST can have side effects for which the user can be held accountable, for example, updating stored data or buying items online.

        If the HTTP POST request is incorrectly formatted, doPost returns an HTTP "Bad Request" message.

        Overrides:
        doPost in class HttpServlet
        Parameters:
        request - an HttpServletRequest object that contains the request the client has made of the servlet
        response - an HttpServletResponse object that contains the response the servlet sends to the client
        Throws:
        java.io.IOException - if an input or output error is detected when the servlet handles the request
        ServletException - if the request for the POST could not be handled
        See Also:
        ServletOutputStream, ServletResponse.setContentType(java.lang.String)
      • doPut

        protected void doPut​(HttpServletRequest req,
                             HttpServletResponse resp)
                      throws ServletException,
                             java.io.IOException
        Description copied from class: jakarta.servlet.http.HttpServlet
        Called by the server (via the service method) to allow a servlet to handle a PUT request. The PUT operation allows a client to place a file on the server and is similar to sending a file by FTP.

        When overriding this method, leave intact any content headers sent with the request (including Content-Length, Content-Type, Content-Transfer-Encoding, Content-Encoding, Content-Base, Content-Language, Content-Location, Content-MD5, and Content-Range). If your method cannot handle a content header, it must issue an error message (HTTP 501 - Not Implemented) and discard the request. For more information on HTTP 1.1, see RFC 2616 .

        This method does not need to be either safe or idempotent. Operations that doPut performs can have side effects for which the user can be held accountable. When using this method, it may be useful to save a copy of the affected URL in temporary storage.

        If the HTTP PUT request is incorrectly formatted, doPut returns an HTTP "Bad Request" message.

        Overrides:
        doPut in class HttpServlet
        Parameters:
        req - the HttpServletRequest object that contains the request the client made of the servlet
        resp - the HttpServletResponse object that contains the response the servlet returns to the client
        Throws:
        ServletException - if the request for the PUT cannot be handled
        java.io.IOException - if an input or output error occurs while the servlet is handling the PUT request
      • executePartialPut

        protected java.io.File executePartialPut​(HttpServletRequest req,
                                                 ContentRange range,
                                                 java.lang.String path)
                                          throws java.io.IOException
        Handle a partial PUT. New content specified in request is appended to existing content in oldRevisionContent (if present). This code does not support simultaneous partial updates to the same resource.
        Parameters:
        req - The Servlet request
        range - The range that will be written
        path - The path
        Returns:
        the associated file object
        Throws:
        java.io.IOException - an IO error occurred
      • doDelete

        protected void doDelete​(HttpServletRequest req,
                                HttpServletResponse resp)
                         throws ServletException,
                                java.io.IOException
        Description copied from class: jakarta.servlet.http.HttpServlet
        Called by the server (via the service method) to allow a servlet to handle a DELETE request. The DELETE operation allows a client to remove a document or Web page from the server.

        This method does not need to be either safe or idempotent. Operations requested through DELETE can have side effects for which users can be held accountable. When using this method, it may be useful to save a copy of the affected URL in temporary storage.

        If the HTTP DELETE request is incorrectly formatted, doDelete returns an HTTP "Bad Request" message.

        Overrides:
        doDelete in class HttpServlet
        Parameters:
        req - the HttpServletRequest object that contains the request the client made of the servlet
        resp - the HttpServletResponse object that contains the response the servlet returns to the client
        Throws:
        ServletException - if the request for the DELETE cannot be handled
        java.io.IOException - if an input or output error occurs while the servlet is handling the DELETE request
      • checkIfHeaders

        protected boolean checkIfHeaders​(HttpServletRequest request,
                                         HttpServletResponse response,
                                         WebResource resource)
                                  throws java.io.IOException
        Check if the conditions specified in the optional If headers are satisfied.
        Parameters:
        request - The servlet request we are processing
        response - The servlet response we are creating
        resource - The resource
        Returns:
        true if the resource meets all the specified conditions, and false if any of the conditions is not satisfied, in which case request processing is stopped
        Throws:
        java.io.IOException - an IO error occurred
      • rewriteUrl

        protected java.lang.String rewriteUrl​(java.lang.String path)
        URL rewriter.
        Parameters:
        path - Path which has to be rewritten
        Returns:
        the rewritten path
      • serveResource

        protected void serveResource​(HttpServletRequest request,
                                     HttpServletResponse response,
                                     boolean content,
                                     java.lang.String inputEncoding)
                              throws java.io.IOException,
                                     ServletException
        Serve the specified resource, optionally including the data content.
        Parameters:
        request - The servlet request we are processing
        response - The servlet response we are creating
        content - Should the content be included?
        inputEncoding - The encoding to use if it is necessary to access the source as characters rather than as bytes
        Throws:
        java.io.IOException - if an input/output error occurs
        ServletException - if a servlet-specified error occurs
      • parseContentRange

        protected ContentRange parseContentRange​(HttpServletRequest request,
                                                 HttpServletResponse response)
                                          throws java.io.IOException
        Parse the content-range header.
        Parameters:
        request - The servlet request we are processing
        response - The servlet response we are creating
        Returns:
        the partial content-range, null if the content-range header was invalid or #IGNORE if there is no header to process
        Throws:
        java.io.IOException - an IO error occurred
      • parseRange

        protected Ranges parseRange​(HttpServletRequest request,
                                    HttpServletResponse response,
                                    WebResource resource)
                             throws java.io.IOException
        Parse the range header.
        Parameters:
        request - The servlet request we are processing
        response - The servlet response we are creating
        resource - The resource
        Returns:
        a list of ranges, null if the range header was invalid or #FULL if the Range header should be ignored.
        Throws:
        java.io.IOException - an IO error occurred
      • render

        protected java.io.InputStream render​(HttpServletRequest request,
                                             java.lang.String contextPath,
                                             WebResource resource,
                                             java.lang.String encoding)
                                      throws java.io.IOException,
                                             ServletException
        Decide which way to render. HTML or XML.
        Parameters:
        request - The HttpServletRequest being served
        contextPath - The path
        resource - The resource
        encoding - The encoding to use to process the readme (if any)
        Returns:
        the input stream with the rendered output
        Throws:
        java.io.IOException - an IO error occurred
        ServletException - rendering error
      • renderXml

        protected java.io.InputStream renderXml​(HttpServletRequest request,
                                                java.lang.String contextPath,
                                                WebResource resource,
                                                javax.xml.transform.Source xsltSource,
                                                java.lang.String encoding)
                                         throws java.io.IOException,
                                                ServletException
        Return an InputStream to an XML representation of the contents this directory.
        Parameters:
        request - The HttpServletRequest being served
        contextPath - Context path to which our internal paths are relative
        resource - The associated resource
        xsltSource - The XSL stylesheet
        encoding - The encoding to use to process the readme (if any)
        Returns:
        the XML data
        Throws:
        java.io.IOException - an IO error occurred
        ServletException - rendering error
      • renderHtml

        protected java.io.InputStream renderHtml​(HttpServletRequest request,
                                                 java.lang.String contextPath,
                                                 WebResource resource,
                                                 java.lang.String encoding)
                                          throws java.io.IOException
        Return an InputStream to an HTML representation of the contents of this directory.
        Parameters:
        request - The HttpServletRequest being served
        contextPath - Context path to which our internal paths are relative
        resource - The associated resource
        encoding - The encoding to use to process the readme (if any)
        Returns:
        the HTML data
        Throws:
        java.io.IOException - an IO error occurred
      • renderSize

        protected java.lang.String renderSize​(long size)
        Render the specified file size (in bytes).
        Parameters:
        size - File size (in bytes)
        Returns:
        the formatted size
      • renderTimestamp

        protected java.lang.String renderTimestamp​(long timestamp)
        Render the specified file timestamp.
        Parameters:
        timestamp - File timestamp
        Returns:
        the formatted timestamp
      • getReadme

        protected java.lang.String getReadme​(WebResource directory,
                                             java.lang.String encoding)
        Get the readme file as a string.
        Parameters:
        directory - The directory to search
        encoding - The readme encoding
        Returns:
        the readme for the specified directory
      • findXsltSource

        protected javax.xml.transform.Source findXsltSource​(WebResource directory)
                                                     throws java.io.IOException
        Return a Source for the xsl template (if possible).
        Parameters:
        directory - The directory to search
        Returns:
        the source for the specified directory
        Throws:
        java.io.IOException - an IO error occurred
      • checkSendfile

        protected boolean checkSendfile​(HttpServletRequest request,
                                        HttpServletResponse response,
                                        WebResource resource,
                                        long length,
                                        Ranges.Entry range)
        Check if sendfile can be used.
        Parameters:
        request - The Servlet request
        response - The Servlet response
        resource - The resource
        length - The length which will be written (will be used only if range is null)
        range - The range that will be written
        Returns:
        true if sendfile should be used (writing is then delegated to the endpoint)
      • checkIfMatch

        protected boolean checkIfMatch​(HttpServletRequest request,
                                       HttpServletResponse response,
                                       WebResource resource)
                                throws java.io.IOException
        Check if the if-match condition is satisfied.
        Parameters:
        request - The servlet request we are processing
        response - The servlet response we are creating
        resource - The resource
        Returns:
        true if the resource meets the specified condition, and false if the condition is not satisfied, in which case request processing is stopped
        Throws:
        java.io.IOException - an IO error occurred
      • checkIfModifiedSince

        protected boolean checkIfModifiedSince​(HttpServletRequest request,
                                               HttpServletResponse response,
                                               WebResource resource)
        Check if the if-modified-since condition is satisfied.
        Parameters:
        request - The servlet request we are processing
        response - The servlet response we are creating
        resource - The resource
        Returns:
        true if the resource meets the specified condition, and false if the condition is not satisfied, in which case request processing is stopped
      • checkIfNoneMatch

        protected boolean checkIfNoneMatch​(HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebResource resource)
                                    throws java.io.IOException
        Check if the if-none-match condition is satisfied.
        Parameters:
        request - The servlet request we are processing
        response - The servlet response we are creating
        resource - The resource
        Returns:
        true if the resource meets the specified condition, and false if the condition is not satisfied, in which case request processing is stopped
        Throws:
        java.io.IOException - an IO error occurred
      • checkIfUnmodifiedSince

        protected boolean checkIfUnmodifiedSince​(HttpServletRequest request,
                                                 HttpServletResponse response,
                                                 WebResource resource)
                                          throws java.io.IOException
        Check if the if-unmodified-since condition is satisfied.
        Parameters:
        request - The servlet request we are processing
        response - The servlet response we are creating
        resource - The resource
        Returns:
        true if the resource meets the specified condition, and false if the condition is not satisfied, in which case request processing is stopped
        Throws:
        java.io.IOException - an IO error occurred
      • generateETag

        protected java.lang.String generateETag​(WebResource resource)
        Provides the entity tag (the ETag header) for the given resource. Intended to be over-ridden by custom DefaultServlet implementations that wish to use an alternative format for the entity tag.
        Parameters:
        resource - The resource for which an entity tag is required.
        Returns:
        The result of calling WebResource.getETag() on the given resource
      • copy

        protected void copy​(java.io.InputStream is,
                            ServletOutputStream ostream)
                     throws java.io.IOException
        Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
        Parameters:
        is - The input stream to read the source resource from
        ostream - The output stream to write to
        Throws:
        java.io.IOException - if an input/output error occurs
      • copy

        protected void copy​(java.io.InputStream is,
                            java.io.PrintWriter writer,
                            java.lang.String encoding)
                     throws java.io.IOException
        Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
        Parameters:
        is - The input stream to read the source resource from
        writer - The writer to write to
        encoding - The encoding to use when reading the source input stream
        Throws:
        java.io.IOException - if an input/output error occurs
      • copy

        protected void copy​(WebResource resource,
                            long length,
                            ServletOutputStream ostream,
                            Ranges.Entry range)
                     throws java.io.IOException
        Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
        Parameters:
        resource - The source resource
        length - the resource length
        ostream - The output stream to write to
        range - Range the client wanted to retrieve
        Throws:
        java.io.IOException - if an input/output error occurs
      • copy

        protected void copy​(WebResource resource,
                            long length,
                            ServletOutputStream ostream,
                            Ranges ranges,
                            java.lang.String contentType)
                     throws java.io.IOException
        Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
        Parameters:
        resource - The source resource
        length - the resource length
        ostream - The output stream to write to
        ranges - Enumeration of the ranges the client wanted to retrieve
        contentType - Content type of the resource
        Throws:
        java.io.IOException - if an input/output error occurs
      • copyRange

        protected java.io.IOException copyRange​(java.io.InputStream istream,
                                                ServletOutputStream ostream)
        Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
        Parameters:
        istream - The input stream to read from
        ostream - The output stream to write to
        Returns:
        Exception which occurred during processing
      • copyRange

        protected java.io.IOException copyRange​(java.io.Reader reader,
                                                java.io.PrintWriter writer)
        Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
        Parameters:
        reader - The reader to read from
        writer - The writer to write to
        Returns:
        Exception which occurred during processing
      • copyRange

        protected java.io.IOException copyRange​(java.io.InputStream istream,
                                                ServletOutputStream ostream,
                                                long start,
                                                long end)
        Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
        Parameters:
        istream - The input stream to read from
        ostream - The output stream to write to
        start - Start of the range which will be copied
        end - End of the range which will be copied
        Returns:
        Exception which occurred during processing