Sunday, 21 May 2017

Serve static resources from external folder outside webapps tomcat

This is quite an important blog for all folks who is looking on how to serve static content from a location on a disk which is completely outside of the webapps folder in Apache Tomcat. This method is quite useful to server images, JS, CSS, PDFs and even static HTML web pages.

Tomcat will serve any static content from a WAR file using the DefaultServlet. This works great for serving files that are bundled with your Java code inside of a WAR file – it’s fast enough for most purposes and it just works, but with one major drawback: you have to re-deploy the WAR file if you want to add or amend a static file.

Tomcat can be configured to read files from anywhere on the disk and serve on a specific URL. This configuration is completely separate to our application configuration.

You just need to change a single file server.xml that resides under $CATALINA_HOME/config/server.xml.

Just open the server.xml file and make the changes like below.

Remember: You need to take bounce of server after the making the changes to take effect of the changes.

<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
   
  <Context docBase="C:\Ankur\testFiles"  path="/companyLogo" />

       <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

</Host>

A <context>  element is added inside the <HOST>  element. Context has two attributes: docBase is the directory on disk that contains your static files and path is the URL that you want to serve the files on. 

Make sure that Tomcat has access to read the files in docBase. Using the example server.xml snippet above, if we had an image in C:\Ankur\testFiles called test.png then we would be able to access it via local Tomcat instance using http://localhost:8081/companyLogo/test.png.

Let's see the example below:

1) Put files inside the C:\Ankur\testFiles directoy

2) Hit the URL: http://localhost:8081/companyLogo/7.png and see the result:




That's it !!

2 comments:

  1. Is there a way where we can supress the error which comes if the path of docBase is not present

    ReplyDelete