问题
I got a situation that I must serve files from different folders then the one of the context my web app is running. As an example, suppose my web app is running in a servlet context on "/opt/tomcat/webapps/ROOT/" and I must serve files existent in "/opt/my_other_folder/". These folders can be changed in runtime by the client, so I can't simply add a new context pointing to these directories. I would like a solution that I wouldn't have to rewrite a web server only for that. Also, the product I work on is generic, so I can't have a solution specific to some servlet container.
Thanks!
回答1:
If you're only serving files, I would consider fronting your servlet container with something like Apache HTTP Server, where you could simply use its various directives to provide a "virtual directory" pointing to an easily configured location.
Otherwise, you could write and configure a standard Java servlet that would do essentially the same thing - storing the actual path in a Java properties file that would be read by the servlet. But while this isn't a lot of work, it would be significantly more work that the above Apache HTTP Server solution. This would be very similar to several of the answers posted at Servlet for serving static content . Specifically, you could either use or extend upon Apache Tomcat's DefaultServlet. (There are some Tomcat-specific classes used in here, but they could be easily replaced with generic equivalents.) http://balusc.blogspot.com/2009/02/fileservlet-supporting-resume-and.html looks even closer to what you'd be looking for, and it is completely generic - while still having some additional, significant features.
Either of these options would be very generic, and not specific to any particular servlet container.
来源:https://stackoverflow.com/questions/8659798/serve-files-from-a-folder-different-of-context-directory-in-a-servlet-container