Thursday, January 28, 2016

Spring Framework model naming

It's been 3 months since I'd encountered any quirks! And I've been working on something new!

If you just want the TL;DR, skip to the bottom.

This time round, I came across a weird situation whereby Spring is unable to provide me a model name I'd expect on my JSP. The object was created as "WTSoupModel" (names have been changed, but the pattern remains the same), and you can probably see the issue immediately if you're somewhat familiar with this situation.

The MVC I've been building up had been mostly running smoothly thus far, until this. The controllers, models, and services have been annotated similarly to my previous modules. What went wrong was when I tried accessing this model that was provided by my Controller via the JSP.

I was expecting the name of the model accessible by the JSP to be "wtSoupModel", but it would always return true whenever I test with ${wtSoupModel eq null} until I dug deep enough. Initially, for the sake of the experiment, I added in the model from the sub-module I'd just completed, ReportModel reportModel, and of course, ${reportModel eq null} gave me false, as expected. Then I made sure the WTSoupModel was Serializable. And then I tried renaming it to WanTonSoupModel in full. Aha! It turned out that ${wanTonSoupModel eq null} was false. This means the issue was with the naming, because there wasn't much else to rule out.

Next, I proceeded to find out if there's anyway I could custom the model naming that reaches the JSP. Upon further investigation, I found this that led to this. Experimenting with it in my Controller proved it true.

Final fix (names have been changed):

@RequestMapping(value = "/wantonsoup", method = RequestMethod.GET)
public String viewWTSoupList(Locale locale,
   @ModelAttribute("wtSoupModel") WTSoupModel wtSoupModel,
    ...
   Model model) throws MSBException {
...
}

I still haven't figured out what Spring resolved the original WTSoupModel into by default. Let me know if you do.