1

I had some files in my webapp in a simple folder in the WAR file. The requests were very fast: as soon as the browser cached a file, it did not request the file contents again until the file changed.

Now I put the files in a different location, and implemented a servlet to deliver the files. The code is simple, but the performance drops. This is the minimal example:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">

    <servlet>
        <servlet-name>File</servlet-name>
        <servlet-class>test.FileServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>File</servlet-name>
        <url-pattern>/file/*</url-pattern>
    </servlet-mapping>
</web-app>

FileServlet

public class FileServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        FileSystem fs = FileSystems.getDefault();
        Path path = fs.getPath("/some/folder/", req.getPathInfo());
        Files.copy(path, resp.getOutputStream());
    }
}

How can I improve it, so that I get the same performance as, for instance, tomcat's DefaultServlet?

Christoph Walesch
  • 2,337
  • 2
  • 32
  • 44
  • so just forget the `Files.copy()` method, and just try to buffer and send data. –  Nov 05 '13 at 13:24
  • Check the implementation of `DefaultServlet`: http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/servlets/DefaultServlet.java – Sotirios Delimanolis Nov 05 '13 at 13:24
  • I also suggest you do not response the file with servlet, just give the direct link like the before, and for setting some extra header data, give some hand of servlet `Filter` –  Nov 05 '13 at 13:26
  • @SotiriosDelimanolis The class is quite big... what's the key point here? Supporting `HEAD` requests and setting `Last-Modified`? Evaluating `If-Unmodified-Since`? Is it necessary / helpful to support byte ranges? – Christoph Walesch Nov 05 '13 at 13:40
  • @noise It all depends on your requirement. I was just posting it so you can compare what you are doing in the base case with what Tomcat does. – Sotirios Delimanolis Nov 05 '13 at 13:44

1 Answers1

1

"Last-modified" header can be helpfull, please look section "Cache on the client" here:

http://www.onjava.com/pub/a/onjava/excerpt/jebp_3/index2.html

pasha701
  • 6,831
  • 1
  • 15
  • 22