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
Simply edit the server. xml under $CATALINA_HOME/config/server. xml as below and restart the tomcat. Add the context element inside the host element with two attribute docBase and path.
The webapps directory is where deployed applications reside in Tomcat. The webapps directory is the default deployment location, but this can be configured with the appBase attribute on the <Host> element.
In a subdirectory of the work directory ... which is where Tomcat conventionally puts transitory files such as compiled JSPs. In a custom subdirectory of the Tomcat installation directory. In a separate directory somewhere else in the file system.
This is the way I did it and it worked fine for me. (done on Tomcat 7.x)
Add a <context>
to the tomcat/conf/server.xml
file.
Windows example:
<Context docBase="c:\Documents and Settings\The User\images" path="/project/images" />
Linux example:
<Context docBase="/var/project/images" path="/project/images" />
Like this (in context):
<Server port="8025" shutdown="SHUTDOWN"> ... <Service name="Catalina"> ... <Engine defaultHost="localhost" name="Catalina"> ... <Host appBase="webapps" autoDeploy="false" name="localhost" unpackWARs="true" xmlNamespaceAware="false" xmlValidation="false"> ... <!--MAGIC LINE GOES HERE--> <Context docBase="/var/project/images" path="/project/images" /> </Host> </Engine> </Service> </Server>
In this way, you should be able to find the files (e.g. /var/project/images/NameOfImage.jpg
) under:
http://localhost:8080/project/images/NameOfImage.jpg
You 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With