Moss

Java Components

 

Redirect Filter

This filter provides a simple way to redirect to different pages, based on regular expression matches of the current URL.

How to Use this Component

Dependencies

This component has no external dependencies.

Installation

To use this component, you must include the .jar file in the web application's classpath (either in WEB-INF/lib or in the server's lib folder). You must then add the following code to the web.xml file:

 <filter>
  <filter-name>RedirectFilter</filter-name>
  <filter-class>org.homeunix.thecave.moss.jsp.redirect.RedirectFilter</filter-class>
  <init-param>
   <param-name>config</param-name>
   <param-value>redirect.xml</param-value>
  </init-param>
  <init-param>
   <param-name>refresh-interval</param-name>
   <param-value>5</param-value>
  </init-param>
 </filter>

 <filter-mapping>
  <filter-name>RedirectFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

Make sure to place this filter above any other filters which you would want to redirect to.

Configuration

The Redirect Filter takes two optional init-params: config and refresh-interval. Config specifies the name of the config file (relative to WEB-INF), and defaults to redirect.xml. Refresh-interval specifies how frequently (in seconds) the config gets invalidated, and must be loaded again next request. This defaults to 60 seconds; for development you may want to reduce this (so that changes to the file are instantly registered; for stable web servers you may want to increast this to 10 minutes or something, depending on server load.

The redirect.xml file is very simple, with a root element redirects wrapping zero or more redirect elements. Each redirect element has exactly one pattern and exactly one destination children elements. The pattern data is matched against the calling URL. If a match is found, it calls a redirect to the URL pointed to in the text of the element. See for instance the sample file below:

<?xml version="1.0"?>
<redirects xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
  xsi:noNamespaceSchemaLocation='http://moss.thecave.homeunix.org/schema/2009/Redirect'>
 <redirect>
  <pattern><![CDATA[(.*)/deutsch/(.*)$]]></pattern>
  <destination><![CDATA[destination="$1/de/$2]]></destination>
 </redirect>
 <redirect>
  <pattern><![CDATA[(.*)/(?!en)(\w{2})/(\w*\.jsp)?]]></pattern>
  <destination><![CDATA[http://translate.google.com/translate?hl=$2&sl=en&u=$1/en/$3]]></destination>
 </redirect>
</redirects>

Note that it is a good idea to wrap the element text in CDATA to ignore any invalid XML characters.