Spring MVC
Spring MVC
Richard Paul
Kiwiplan NZ Ltd
27 Mar 2009
What is Spring MVC
This is the low level interface for controllers, most of the time you will not use
the Controller interface directly.
The ModelAndView, is an object that holds the model objects as well as the
view required to be rendered (simplified definition).
Controller Annotations
@Controller
public class ItemController {
@RequestMapping(value="viewItem.htm", method=RequestMethod.GET)
public Item viewItem(@RequestParam Long id) {
return itemService.get(id);
}
By convention a view with the name 'viewItem' (based on the request mapping URL) will be
used to render the item.
Session attributes
@Controller
@RequestMapping("editItem.htm")
@SessionAttribute("item")
public class ItemEditorController {
@RequestMapping(method=RequestMethod.GET)
public String setupForm(@RequestParam Long itemId, ModelMap model) {
Item item = ...; // Fetch item to edit
model.addAttribute("item", item);
return "itemForm";
}
@RequestMapping(method=RequestMethod.POST)
public String processSubmit(@ModelAttribute("item") Item item) {
// Store item
// ...
return "redirect:/viewItem.htm?item=" + item.getId();
}
}
A GET to 'editItem.htm' adds the item with the given ID to the user's session. When a POST is made, this
item is pulled from the session and provided as an argument to the processSubmit method.
Flexible Method Arguments
Return Type
String // View name
ModelAndView // Model objects and view name
Item // Or other object, assumed to be the model object
void // This method handles writing to the response itself
http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html#mvc-ann-
requestmapping-arguments
Testability
@Test
public void viewWithValidId() {
Item item = new Item(3l);
when(itemService.get(3l)).thenReturn(item);
assertEquals(item, controller.view(3l));
}
Testability - with model attributes
@Test
public void submitItem() {
Item item = new Item(3l);
controller.submitItem(item);
verify(itemService.save(item));
}
@InitBinder
public void initBinder(DataBinder binder) {
// Register a new editor each time as they are not thread safe
binder.registerCustomEditor(
Category.class, new CategoryPropertyEditor());
}
Validation
Errors are stored in the Errors object, if any errors are present, the form can be
redisplayed with error messages instead of following the normal form submission.
Views
</form:form>
Form tags are include for all HTML input types, e.g. form:radio, form:textarea
Resolving Messages
Spring Reference
http://static.springframework.org/spring/docs/2.5.x/reference/