我的 webapp 中有一些文件位于 WAR 文件的一个简单文件夹中。请求非常快:一旦浏览器缓存了一个文件,它就不会再次请求文件内容,直到文件发生变化。
现在我将文件放在不同的位置,并实现了一个 servlet 来传递文件。代码很简单,但性能下降。这是最小的例子:
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>
文件服务程序
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());
}
}
如何改进它,以便获得与例如 tomcat 相同的性能DefaultServlet
?