Virtual Directories in Glassfish

There are many reasons you may want some of your content outside of the application server root. Perhaps you wish to share the content between applications or even webservers, or maybe you temporarily write data from a database to be served. Regardless, serving static content in glassfish is extremely easy. There are two ways to accomplish this; at the server level and at the application level.

Server level

First we will look at the server level, this will make your information available server wide, outside of any application context. Lets say you have images you wish to serve in the directory C:\media. In the glassfish admin console expand configuration > http service > virtual servers. Select ‘server’ then scroll to the bottom and select ‘add property’.

For name use: alternatedocroot_1, for value use: from=/media/* dir=C:/

Keep in mind that glassfish expects the directory in the URL pattern to exist, so the from= is not just the URL pattern, but it is also the path relative to the dir=.

Luckily these changes do not require any restarts so you can experiment easily to make sure you have the settings you want. If you used the default glassfish install and your server runs at http://localhost:8080 then http://localhost:8080/media/ should now resolve to the absolute path C:\media.

Using virtual directories in Glassfish.

The image above shows adding an alternate docroot from in the admin console, click it for the full sized image.

Application Level

Let’s say you have an application WebApplication1. By editing sun-web.xml you can add an alternate docroot that is relative to the application. For this example I will use the same as above, serving /media/* from C:/.

Add the following line to sun-web.xml inside the <sun-web-app> tag:

<property name=”alternatedocroot_1″ value=”from=/media/* dir=C:/”/>

If using the default glassfish setup, http://localhost:8080/WebApplication1/media/ should now resolve to the absolute directory C:\media

alternate docroot in sun-web.xml

The image above shows an example of sun-web.xml. Click for full size.

In both of the above scenarios you can have as many alternate docroots as you want, as long as the follow the naming convention (alternatedocroot_1, alternatedocroot_2, etc…). Also your url pattern can be as specific as you like, for instance if you only wanted to catch requests for jpeg’s in the media directory then you would use: from=/media/*.jpg


5 Responses to “Virtual Directories in Glassfish”

Leave a Reply