Setting the default request format for a Rails app

While working on an external api for an application we are developing at the moment  (we being the company I work for,, I came across a small problem which I could not find the answer for, how to set the default response format for a url or set of urls (eg. /people  would use display xml to the client without the need for the .xml extension or format=xml querystring parameter).

Well, I personally could not find any good sample code to do so, I did find one at the Ruby is Beautiful blog which suggested a bit of code that modified the request headers and request environment but not using the rails conventions, it was a bit intrusive for my liking. So I instead decided to see if there was a better was to go about this.

Solving the problem turned out to be quite easy. Rails uses two methods to determine what response format to use, the first is the request header, and the second is the request parameter ‘format’, with the latter taking priority over the former. Have a read up on Routes Inside Out at Rails Guides for a bit more information on the request header. I also recommend you get your hands dirty with some of the internal workings of the rails code base, have a read into request.rb of actionpack (2.2.2) (line 144), as well as mime_responds.rb. 

Anyhow, the simple code is as follows….

  before_filter :set_default_response_format


    def set_default_response_format
      request.format = 'xml'.to_sym if params[:format].nil?

Sorry but due to WordPress formatting, I had to use the to_sym method instead of just a straight symbol as WordPress would then turn it into one of those annoying smiley face images.

Anyhow, as you can see, if the url is missing a .<ext> or ?format=<ext> (both of which are then added to params[:format]) then the default request format is set to :xml (see what I mean, annoying smiley face image!), which is normally :html or decided from the Accept header. (The Rails docs pretty much tell you how to use the format= method – RailsBrain)

I hope this helps,




Filed under Rails

my long awaited return

Its been a long time, well, 6 months, and a lot has changed. First off I have left my job with the Ministry of Social Development in New Zealand. This was because (second change) I have moved overseas (after three months traveling) to Amsterdam in the Netherlands. And third major change, I have changed my preferred language of choice to Ruby (and Rails) from Java (Spring MVC). I have gone from being a Java Developer to being a Jnr Ruby Developer. 

So who do I work for now? I start on Monday with a company called TTY based in Amsterdam ( as a jnr Ruby Developer. But don’t expect to leave my Java roots entirely as I know I have a long way to go to become a real Ruby Developer, but expect to see a change in this blog over time.

The resurrection of this blog has been in part due to blog08 ( which I am at today, which reminded me the reasons I started this blog (thanks to Pete Cashmore from Mashable). 

Anyhow, I best run, but talk to you all soon.

Leave a comment

Filed under Updates

Handling Exceptions In Spring MVC – Part 2

In ‘Handling Exceptions In Spring MVC – Part 1’ we talked about how the servlet container can be set up to manage exceptions and status codes, as well as some of the issues you can face by having the servlet container be responsible for this. We also went over the HandlerExceptionResolver interface in Spring, including the SimpleMappingExceptionResolver implementation which is an excellent base for extension.

In this post I am going to show a possible extension to the SimpleMappingExceptionResolver – one which allows us to define exception priorities as well as sending different notifications based on the priorities. Included at the bottom of this post is a link to a sample web app which shows the use of the SimpleMappingExceptionResolver and the newly created one shown in the post. The web app uses both the 2.0 and 2.5 styled controllers and is only meant as a small example.

I mentioned in the previous post that this would be a ‘two post’ post. Well, after sitting down and planning out what I would like to cover, it seems it might be three posts, sorry. Also I would be very interested in other people’s views on this topic, as I believe there is no ‘right’ answer, but instead a different set of answers for a different set of situations.

Quick Refresh

The SimpleMappingExceptionResolver is a perfectly good implementation of the HandlerExceptionResolver interface. Its basic configuration is like so :

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
    <entry key="DataAccessException" value="data-error" />
    <entry key="com.stuff.MyAppRuntimeException" value="app-unchecked-error" />
    <entry key="com.stuff.MyAppCheckedException" value="app-checked-error" />
<property name="defaultErrorView" value="general-error"/>

The above example shows three features of the SimpleMappingExceptionResolver (SMER) :

  1. default error page – All exceptions, checked and unchecked, will be resolved to either a specific page individual to them, or to a generic page which is set by the defaultErrorView.
  2. specific exceptions – As per the above example, “app-unchecked-error” and “app-checked-error” are the views to “com.stuff.MyAppCheckedException” and “com.stuff.MyAppRuntimeException” respectively.
  3. substring and subclass support – DataAccessException will match to org.springframework.dao.DataAccessException and com.myapp.DataAccessException, including any subclasses of either.

Have you read the SMER api docs? If you haven’t, READ IT!!!, it’s a wealth of information. In fact, if you really want to learn, have a look at the source code, download it from the Spring website and nosey through it, it’s the only true way to learn the api.

Extending SimpleMappingExceptionResolver – Stage One

Okay, enough about the SMER, let’s get onto extending. For our new HandlerExceptionResolver we should define some simple and clear requirements:

  1. When an Exception is handled by the resolver, a notification might be sent out
  2. Several different Notification services can be set up, each with a priority (user definable)
  3. Exceptions can be assigned a priority as to determine which Notification service to use
  4. If no priority is defined for an Exception then no notification is to be sent
  5. All exceptions handled should be logged with the priority assigned to the Exception type

Is that enough? Well, for this example it is. I am going to only show a possible way of extending SMER; not the perfect implementation, just a possible one.

For this we are going to need a NoficationService interface:

public interface NotificationService {
  public void sendNotification(String message, Exception exception);

And a simple implementation which will send an email:

import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

public class EmailNotificationEmail implements NotificationService {
  private MailSender mailSender;
  private SimpleMailMessage templateMessage;

  public static final Log log = LogFactory.getLog(EmailNotificationService.class);

  public EmailNotificationService(MailSender mailSender, SimpleMailMessage templateMessage){
    this.mailSender = mailSender;
    this.templateMessage = templateMessage;

  public void sendNotification(String message, Exception exception) {

    SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
    msg.setText("Application Message - " + message + " : " + exception.getMessage());

    } catch(MailException ex) {
      // simply log it and go on...
      log.fatal("Email Notification message could not sent", ex);

(have a read here about the email apis provided by Spring)

And this is to go in the applicationContext-services.xml

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value=""/>

<!-- this is a template message that we can pre-load with default state -->
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="to" value=""/>
<property name="from" value=""/>
<property name="subject" value="My-App has had a fatal exception occur"/>

<bean id="emailNotificationService" class="com.example.myapp.EmailNotificationService">
  <constructor-arg><ref bean="mailSender"></constructor-arg>
  <constructor-arg><ref bean="templateMessage"/></constructor-arg>

So far we have a NotificationService interface, EmailNotificationService implementation, and an application context to wire it all up. So now we need to create the SMER extension.

Extending SimpleMappingExceptionResolver – Stage Two

Below is the code for the NotifyingExceptionResolver. Please remember that formatting of the code isn’t great, but all code is available for download at the end of the post.

public class NotifyingExceptionResolver extends  SimpleMappingExceptionResolver {
  private Properties priorityExpMappings;
  private Map priorityNSMappings;
  private String notificationMessage = null;

  private Log log = LogFactory.getLog(NotifyingExceptionResolver.class);

  public void setPriorityExceptionMappings(Properties  priorityExpMappings){
    this.priorityExpMappings = priorityExpMappings;

  public void setPriorityNotificationServicesMappings (Map priorityNSMappings){
    this.priorityNSMappings = priorityNSMappings;

  public void setNotificationMessage(String message){
    this.notificationMessage = message;

  protected ModelAndView doResolveException(HttpServletRequest request,  HttpServletResponse response, Object handler, Exception ex) {
    log.warn("An Exception has occured in the application", ex);
    return super.doResolveException(request, response, handler, ex);

  private void sendNotification(Exception ex) {
    String priority = resolvePriority(this.priorityExpMappings, ex);
    NotificationService notificationService = resolveNotificationService (this.priorityNSMappings, priority);
    String message = (notificationMessage == null ? priority :  notificationMessage);

    if(notificationService != null) {
      log.debug("notification message was sent");
      notificationService.sendNotification(message, ex);

  private String resolvePriority(Properties priorityExpMappings,  Exception ex){
    return this.findMatchingViewName(priorityExpMappings, ex);

  private NotificationService resolveNotificationService (Map priorityNSMappings, String priority){
    NotificationService notificationService = null;
    notificationService = priorityNSMappings.get(priority);
    if (notificationService != null && logger.isDebugEnabled()) {
      logger.debug("Resolving to a notification service for priority ["  + priority + "]");
    return notificationService;

You will notice two important variables – priorityExpMappings and priorityNSMappings. These variables hold the mappings between the exception types, priorities and notification services. You will also notice the method I have used as my hook in, doResolveException. As this method is where the action is, all I have done is added some more behavior and then called the super method. I have cheated a bit in the resolvePriority method by using the smarts behind findMatchingViewName to determine the priority linked to the exception. From there on in it’s pretty straightforward; I determine the priority based on the exception, find the notification service, and send a message.

Here is the application context definition which goes with it :

<bean class="com.mycompany.myapp.web.exceptionresolvers.NotifyingExceptionResolver">
<property name="exceptionMappings">
      <entry key="SpecialCheckedApplicationError" value="errors/checked-error"/>
      <entry key="SpecialRuntimeApplicationError" value="errors/runtime-error"/>
<property name="priorityExceptionMappings">
      <entry key="SpecialRuntimeApplicationError" value="High" />
      <entry key="SpecialCheckedApplicationError" value="High" />
<property name="priorityNotificationServicesMappings">
      <entry key="High" value-ref="emailNotificationService" />
<property name="defaultErrorView" value="errors/general-error" />

You will notice that I still define the exceptionMappings property and the defaultErrorView property. There is no doubt I have extended from the SMER; I have just added some cherries to an already creamed pie.

Would this be the best option all the time?

Is extending the SimpleMappingExceptionResolver best for all cases? No, nothing is best for all cases, but it is best for most. In fact, just using the SMER and not extending it is best for most, and extending it is only for required cases. To be honest, creating a notification system like I have is quite contrived as the logging system can use an smtp gateway to do what I have done, and creating new logging appenders isn’t hard either.

I have a lot more to cover and talk about, but this post is already 1000+ words. The final post in the series will expand on the question of what errors should be captured where; be it in the web.xml, controller, or handler exception resolver, checked and runtime.

This post merely shows that extending and customizing the SMER is not hard and very feasible, but just make sure you know why you are doing it.

Sample Application

To download the sample web app with email notification service, click here. This web app is built using Maven and thus requires a bit of knowledge of Maven to package up. If you’re not a Maven fan then it shouldn’t be that hard to refactor into a single package and source folder.

(Please note, make sure you download Spring MVC 2.5.2, 2.5.1 has issues with annotated controllers throwing checked exceptions)


Reporting Application Errors by Email (using logging)


Filed under Spring MVC

Stolen blog post? Join the line!

What can you do when someone steals your blog post, word for word, changes the title, and posts it on their site while also refusing to post your comments or reply to your requests to remove it? To be honest, there isn’t much you can do. How do I know? Because its happening to me right now.

Ben Mira (at least, I think that’s his name), author of (DO NOT GO THERE, he has ads on his site and thus makes some money each time someone views his site), stole my blog post about handling exceptions in Spring MVC, without even a mention of the original article which I wrote, or the author – me.

I was flattered at first as I have read posts on the blog before and saw it as a collection of relevant Spring posts. But as I read through the site again, after being alerted to my post being there, I noticed other posts which have been stolen. These, again, have no mention of the original author or post.

What can a boy do?

I did what anyone would do – I wrote a comment on the site. However, I have had no luck with this, as he moderates the comments and has decided to ignore them.

I then lodged a complaint with Blogger, owner of BlogSpot, but this only led to an email from them telling me to write a Notice of Infringement which complies with the Digital Millennium Copyright Act. Well, I have never written one, don’t have a lawyer, make no money from the blog to pay for a lawyer, and don’t come from the US; wow, I certainly feel out of my depth.

I then spoke to my brother, who is a lawyer in London, about my options. He advised me to write another comment giving him 24 hours to remove the post or further action will be taken, but it’s been over 24 hours and relying on a busy lawyer brother to help is dependent on his spare time, which is pretty sparse.

I am not angry that my post has been duplicated; I am angry that I was not mentioned as the author and that my original article was not linked to.

My instincts tell me that this won’t blow over quickly, but if you have any advice or can point me in the right direction please post a comment.

I’ll keep you updated.


Filed under Rants

Common Reference Data in Spring MVC

What is Reference Data?

Does Reference Data differ from Model Information?

Is CSS and image location information Reference/Model Data?

Reference Data is a term used very frequently by Spring MVC developers, especially ones which use the pre-made Spring controllers. The idea of Reference Data has mainly come from the referenceData method, located in the AbstractFormController, which is a base class for both the SimpleFormController and AbstractWizardFormController. The former is a very popular and well used controller in Spring MVC applications. Reference Data is information which is added to the model for use by the view, be it jstl, pdf or freemarker. The terms Model Data and Reference Data are used interchangeably as they are the same; the former is a newer way to refer to information being added to the ‘model’ of the page (Spring 2.5 brought in the new concept of a ‘model map’, where the model is separate to the ModelAndView). This, in itself, paves a very obvious path to the new @ModelAttribute annotation which has appeared in Spring 2.5, a new way to add Reference Data (or Model information) to the ModelMap. Have I lost you?

Reference Data can be of two forms – page specific and application/site specific. Page model data could be lists of products, product categories, number of users on the site or simply data to go into lists and combo boxes, for example. Application/site specific model data is usually simpler and narrower in scope, for example, css and image locations.

This post is going to focus on site / application reference data. I don’t want to delve into too much of the already known (2.0 reference data), instead I would like to focus on the @ModelAttribute annotation and using Interceptors for adding this data to your ModelMap / ModelAndView.

1. model attribute on every set of reference data

The first example is the simplest but not the cleanest; simply put we are going to add the page specific data using individual @ModelAttribute annotated methods.

public class SimplePage {

public String cssLocation(){
return “;;

public String imageLocations(){
return “;;

public String showSimplePage(ModelMap model){

model.addAttribute(“stuff”, “importantStuff”);

return “simplePage”;

This is fine for one or two controller, but we can do better.

2. model attribute on every set of reference data in a super class

This is very similar to the first example, except now we are adding the @ModelAttribute methods into a super class which our other controllers can extend.

public abstract class AbstractCommonModelDataController {

public String cssLocation(){
return “;;

public String imageLocations(){
return “;;


This is better than the first example as we have now grouped common behaviour into a super class. This approach is good for a couple of pieces of reference data, but not for many as it becomes a bit messy.

3. model attribute on one method for large common set of reference data, all in a super class

Okay, so as the title says, we are going to use the helpful autowiring magic Spring MVC weaves and have only one method for the model data.

public abstract class AbstractCommonModelDataController {

public void cssLocation(ModelMap model){
model.addAttribute(“cssLocation”, “;);
model.addAttribute(“imageLocation”, “;);

This is a nice solution, an is very clean and very simple.

But all the previous examples have a common issue, as all @ModelAttribute methods are run before the handler is executed, if the handler returns a redirect the model data will be added to the url as a query string. This should be avoided at all costs as it could expose some secrets on how you have put together your application. One example I propose, which came out of a forum post I helped answer (read more here), is to create a HandlerInterceptor, which implements the postHandle method and add the model data here. Let’s take a look.

4. HandlerInterceptor for common reference data within the entire web application

(also, just a quick sorry for the crap formatting of the code below, WordPress doesn’t handle code very well)

public class CommonModelMapInformationInterceptor implements
HandlerInterceptor {

// This method is unused as this Interceptor is for post handle only
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception { }

// This method is unused as this Interceptor is for post handle only
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
return true;

public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {

boolean isRedirectView = modelAndView.getView() instanceof RedirectView;
boolean isViewObject = modelAndView.getView() == null;
// if the view name is null then set a default value of true
boolean viewNameStartsWithRedirect = (modelAndView.getViewName() == null ? true : modelAndView.getViewName().startsWith(UrlBasedViewResolver.REDIRECT_URL_PREFIX));

if(modelAndView.hasView() && (
( isViewObject && !isRedirectView) ||
(!isViewObject && !viewNameStartsWithRedirect))){

public void addCommonModelData(ModelAndView modelAndView){
modelAndView.addObject(“stuff”, “importantStuff”);
modelAndView.addObject(“moreStuff”, “moreImportantStuff”);

(Download the HandlerInterceptor here)

I like this approach the most as it abstracts the common reference data out of the controllers and is only applied on views which are not redirects; this could be further improved to only work with certain views only (like jstl, freemarker etc.). This set-up does have one major flaw – postHandle methods on HandlerInterceptors are not called when Exceptions occur during handler processing. This means that if you use the SimpleMappingExceptionResolver then you will need to extend it and possibly inject the interceptor in and call the addCommonModelData method. Otherwise you could look at abstracting the addCommonModelData out of the HandlerInterceptor, put it in its own class, declare it as a bean, and inject it into the HandlerInterceptor and HandlerExceptionResolver. Also to note, a small downside to this approach is that you need to register the HandlerInterceptor with any mappers you use, if it be bean name, simple mapping, or annotation mapping.

I am sure there are more than these four approaches for application specific model data and if you have a suggestion, opinion, question, or comment I would be very keen to hear from you.




Filed under Spring MVC

A quick update : DWR + Spring + NO AOP

I just wanted to write a quick update on my first post : Spring + DWR namespaces + AOP

Jose Noheda, one of the developers of DWR, advised me to log a bug in the DWR Jira. Well, I did, and about 2 days later, low and behold, its fixed, so to speak.

Have a look at the bug report, but in short, instead of having to proxy your service beans via the Spring ProxyBeanFactory, a namespace tag has been created which proxys your bean for you, allowing you to add the <dwr:remote …. /> tags separate from the original service bean definition



<bean id=”mySimpleService” class=”com.sample.SimpleServiceImpl” />


<dwr:proxy-ref bean=”mySimpleService” javascript=”…” >
<dwr:include method=”*” />

Although this has been fixed for version 3.0 M2, version 3 isn’t that far away, its worth the wait. But if you can’t wait, use the other way for now (ProxyFactoryBean) and then switch.

Thanks Joe and Jose for all your work

Leave a comment

Filed under Ajax Integration, Updates

Handling Exceptions In Spring MVC – Part 1

To read Part 2 in this series, click here

New to Spring MVC ?

or maybe you’re experienced ?

or maybe you have just used it a bit, you know, here and there.

Whatever the case, Spring MVC can cater for anyones web development appetite, if it be a simple site using the defaults, or a complex custom configuration utilizing local resolvers, custom handler mappers, and various view resolvers for jstl, freemarker and pdf.

In this post I would like to talk specifically about handling exceptions in your Spring web based application and different ways you can cater for the unexpected (although, if you plan for the unexpected aren’t you then expecting and thus planning for the expected?). Exceptions can occur throughout your application, from your domain layer to your web controllers, and handling them correctly is very important for everyone involved, especially the person on the end of the browser using the application.

As to keep this post readable, as I waffle a bit, I have broken it up into a few different posts, most likely two (but I will see how I go), so I can discuss what you get out of the box with a servlet container, Springs pre-made offerings, and options for building your own and customization.

web.xml and the servlet container

If you are familiar with the servlet spec you will already know that servlet containers can handle exceptions and error codes, all with just a simple declaration within your web.xml. This declaration can look something like this:



Ok then, well, if the servlet container can handle the exceptions (and error codes), why do we need to bother setting up Spring to handle them? Well, there are some good reasons why, but before I explain them I need to explain the difference between an ‘error code’ and exception.

Error codes, or status codes as they are better known, are part of the http rfc spec and are not treated as an exception, per se. Spring does not catch error codes, in fact, it can’t, it can write error codes by calling response.sendError but does not catch them as they are only handled by the servlet container. Some well known status codes include 404 (page not found), 408 (request time-out), 500 (internal server error) and 503 (service unavailable). Status codes can either be caught and handled by the servlet container, which happens in most cases, and have a pretty html page served to the client, or a response can be sent which just contains the status code leaving the client (web browser) to display a page or message to the person on the other end of it. This is not new information, and it is fair to say that since Spring can not handle error codes being raised (as in some cases Spring will be raising them), the web.xml is the best place to handle these error codes.

So then, if web.xml is handling our error codes, why not let it handle our exceptions as well? There are some good reasons (as mentioned before) and they are :

  1. Filters are by-passed – This was a problem which appeared in a development another team was working on in my organization. Sitemesh decorates the pages by working as a servlet filter, if the application came upon an error code or exception, the servlet container would by-pass the filters and just render the jsp. In Spring this would not happen as it would catch the exception and not let it propagate up to the servlet container.
  2. Reference Data – Since the servlet container will just render a page, it will not allow for business logic to run, for example, not populate the model with some reference data.
  3. Logging and Auditing – Again, since only a page is rendered no extra logging, auditing or notifcation can be added cleanly.
  4. and last of all, generally these are Application exceptions and should be handled by the application not a third party.

It sounds like I am advocating Spring should do everything and you should just let the web.xml do only what Spring can’t. Well, thats a combination of yes and no, both Spring and the servlet container need to work together to handle status codes and exceptions properly, but it is also important that each should be used to capture errors and exceptions which they are responsible for.

handling exceptions in Spring

When you declare a DispatcherServlet you get several components out of the box, for example you get a bean name handler mapper, an annotation handler mapper, three or four handler adapters and a view resolver, to name a few of them.

One thing you don’t get is a HandlerExceptionResolver set up for you, but it only takes a second to set one up.

If you’re familiar with the workflow involved with handling a request, you will know that a try catch block surrounds the HandleAdapter method handle in the DispatcherServlets doDispatch method. If an exception occurs the DispatcherServlet will call processHandlerException which will then see if a HandlerExceptionResolver is registered. You can have any number of HandlerExceptionResolvers registered, be it one (which suits for most cases), two, 10, or more, and because they implement the Ordered interface you get to decide which one gets the chance to try and handle the exception first.

The HandlerExceptionResolver is an interface which contains only one method :

ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex)

Spring is nice enough to give you a simple implementation which should be of use to most applications from the get go, its a simple exception resolver (SimpleMappingExceptionResolver) which maps exception types to error pages. Its configuration looks something like :

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<entry key="DataAccessException" value="data-error"/>
<property name="defaultErrorView" value="general-error" />

As you can see all you need to do is create a list of exception types and link them to error pages, a very similar setup to SimpleUrlHandlerMapping.

The SimpleMappingExceptionResolver is a nice stable basic implementation which provides a good solid foundation for building and extending upon. In fact, the Spring team themselves recommend this as they provide many hooks for doing so. This is my first recommendation, use the SimpleMappingExceptionResolver in some shape or form, if it be for your main exception resolver or for extending upon, it provides a good solid base to work from and is very functional.

a quick summary

So far we know that the web.xml can do some things Spring can’t, like catch 404 or 500 status codes, but Spring on the other hand provides a HandlerExceptionResolver implementation which exposes many hooks ready for extension. Should one be used over another, no, should they be used together, well, yes, but its about using them together correctly, a topic I would like to leave until my next post, including possible ways to extend the SimpleMappingExceptionResolver, as this one is getting a bit long.

Thanks for reading


To read Part 2 in this series, click here


Filed under Spring MVC