看来您对BalusC的帖子有误解:FileServlet。在这种情况下,磁盘上将具有一个用于存储文件的基本路径(在服务器中Web应用程序文件夹路径的外部),然后URL中使用的路径将用于
在 该基本路径 内 进行搜索。从BalusC的示例中注意如何调用资源:
<a href="file/foo.exe">download foo.exe</a>
哪里:
- 文件 是Servlet的URL模式。在您的web.xml配置中注意到:
<servlet-mapping> <servlet-name>FileServlet</servlet-name> <url-pattern>/file/*</url-pattern> </servlet-mapping>
- URL /foo.exe 的其余部分是文件在服务器硬盘驱动器中的位置。这可以很容易地通过使用
HttpServletRequest.html#getPathInfo
这是在代码的这一部分中指出的(注释是我的):
public void init() throws ServletException { this.filePath = "/files"; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the file path from the URL. String requestedFile = request.getPathInfo(); //... //using filePath attribute in servletclass as the base path //to lookup for the files, using the requestedFile //path to seek for the existance of the file (by name) //in your server //decoding the name in case of GET request encoding such as //%2F => / File file = new File(filePath, URLDeprer.depre(requestedFile, "UTF-8")); //... }然后,当有这样的请求时(在您的视图中为HTML代码):
<img src="files/img/myimage.png" />
您必须确保文件存在于服务器中:
- / <-- root - /files <-- this is the base file path set in init method in your servlet - /img - myimage.png



