301 Redirects Made Easy In Java

Published Tue, 8 Jun 2010 • 4 comments

I've just released a new version of visural-common - 0.3.2.

This version includes a new Servlet Filter, which makes 301-redirects in Java a breeze.

You'd recall that 301 redirects are useful for SEO (and just general good practice) for when you move content to another place, or to create a "canonical" version of a piece of content. Matt Cutt's has done a few posts about 301 vs. 302 redirects and when you should use each, but this post pretty much summarizes the use-case for this filter.

Using the filter is easy, just create a class that extends from PermanentRedirectFilter:

public class MyRedirect extends PermanentRedirectFilter { public void configureRoutes() { // ... your config goes in here ... // e.g. fromHost("mydomain.com").to("www.mydomain.com"); // urls work too fromURL("http://www.mydomain.com/index.jsp") .to("http://www.mydomain.com/"); fromURL("http://www.mydomain.com/blog/post.jsp?p=123") .to("http://www.mydomain.com/blog/2010/06/how-to-do-301-redirects-in-java"); // you could also use this to move your domain to another place altogether. // The same page url and parameters will be used after the host. fromHost("www.myolddomain.com").to("www.other.com"); } }

Pretty easy and efficient syntax.

You'll then want to add this to your web.xml in the usual way for configuring a filter, e.g.:

<filter> <filter-name>MyRedirectFilter</filter-name> <filter-class>com.mycom.MyRedirectFilter</filter-class> </filter> <filter-mapping> <filter-name>MyRedirectFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

Done and done - that's all there is to it.

About the Author

Richard Nichols is an Australian software engineer with a passion for making things.

Follow him on twitter or subscribe by RSS or email.

You might also enjoy reading -

Discuss / Comment