Friday, January 22, 2010

301 redirects with Wicket

Sometimes a web-page needs to redirect to a new address. A 301 redirect means that a page moved permanently, which in most cases is indistinguishable from a 302 "moved temporarily" redirect. Search engines however react differently to a 301 response than to a 302 response. If a page has moved permanently, sending a 301 will cause the search engine to update its index to the new page. For "important" pages, you would thus prefer sending 301 redirect from an old url to a new url.

Assuming the old url was a .jsp, here is a JSP snippet to send a 301 redirect:
<% 
String redirectURL = "http://.../";
response.setStatus(301);
response.setHeader( "Location", redirectURL);
response.setHeader( "Connection", "close" );
%>

If you are using Wicket, you can instruct the wicket filter in your web.xml file to ignore the said url, otherwise wicket filter would try to serve the JSP page as a Wicket page, which would not work.
<filter>
<filter-name>a name</filter-name>
<filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
<init-param>
<param-name>ignorePaths</param-name>
<param-value>oldURL.jsp,other_urls_to_ignore,...</param-value>
</init-param>
</filter>
For an arbitrary (non-jspP) url, you might actually need to create a wicket page redirecting from the old url to the new one. Here is the relevant code:
public class MyRedirectingPage extends WebPage {
public MyRedirectingPage() {
final String newURL = "http://...";
RedirectRequestTarget target = new RedirectRequestTarget(redirectURL) {
@Override
public void respond(RequestCycle requestCycle) {
WebResponse response = (WebResponse) requestCycle.getResponse();
HttpServletResponse servletResponse = response.getHttpServletResponse();
servletResponse.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
servletResponse.setHeader("Location", newURL);
servletResponse.setHeader("Connection", "close");
}
};
getRequestCycle().setRequestTarget(target);
}
}
Within your WebApplication class, you also need to mount to the old url.
  mountBookmarkablePage("path/to/old/url", MyRedirectingPage.class);

1 comment:

Anonymous said...

This works great! Thanks for the post :)