How can i use Tomcat to serve image files from a public folder outside webapps? I dont want to use a 2nd Apache fileserver on a different port since the image files are part of the same app. And i dont want to create a symlink to the public folder inside webapps since my app is deployed as a war file....Is there a simpler solution similar to using default servlet for static content inside webapps, for static content outside outside webapps
views:
3982answers:
4You could have a redirect servlet. In you web.xml you'd have:
<servlet>
<servlet-name>images</servlet-name>
<servlet-class>com.example.images.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>images</servlet-name>
<url-pattern>/images/*</url-pattern>
</servlet-mapping>
All your images would be in "/images", which would be intercepted by the servlet. It would then read in the relevant file in whatever folder and serve it right back out. For example, say you have a gif in your images folder, c:\Server_Images\smilie.gif. In the web page would be <img src="http:/example.com/app/images/smilie.gif"...
. In the servlet, HttpServletRequest.getPathInfo()
would yield "/smilie.gif". Which the servlet would find in the folder.
Instead of configuring Tomcat to redirect requests, use Apache as a frontend with the Apache Tomcat connector so that Apache is only serving static content, while asking tomcat for dynamic content.
Using the JKmount directive (or others) you could specify exactly which requests are sent to Tomcat.
Requests for static content, such as images, would be served directly by Apache, using a standard virtual host configuration, while other requests, defined in the JKMount directive will be sent to Tomcat workers.
I think this implementation would give you the most flexibility and control on the overall application.
With the redirect servlet, I must be missing something. Do you need to write a controller class to find the file? I don't see how the image file is returned because no where does the example show how it is searching the C:\Server_IMages\ folder for images? I guess I'm wondering what steps or example are missing.
You can deploy an images folder as a separate webapp and define the location of that folder to be anywhere in the file system.
Create a Context element in an XML file in the directory $CATALINA_HOME/conf/[enginename]/[hostname]/
where enginename might be 'Catalina' and hostname might be 'localhost'.
Name the file based on the path URL you want the images to be viewed from, so if your webapp has path 'blog', you might name the XML file blog#images.xml
and so that your images would be visible at example.com/blog/images/
The content of the XML file should be <Context docBase="/filesystem/path/to/images"/>
Be careful not to undeploy this webapp, as that could delete all your images!