Monday, August 18, 2008

@MVC: New Programming Model of Spring Web MVC

In an excellent article, Rossen Stoyanchev of SpringSource presents a bunch of new annotation-based features of Spring Web MVC framework.

Quote:

@MVC changes [Spring Web MVC] programming model in 3 significant ways.

  1. It does not have any interface or base class requirements.
  2. It allows any number of request handling methods.
  3. It allows a high degree of flexibility in the method's signature.

Given those three it's fair to say @MVC is not merely an alternative. It's the next step in the evolution of Spring MVC's controller technology.

The new programming model is an example of a POJO-centric approach that, combined with sensible convention-based defaults, greatly simplifies and facilitates web development based on Spring Web MVC framework.

This is a very welcome change as Spring Web used to be notorious for its verbose and extremely fine-grained configuration. With Spring 2.5 @MVC one can express oneself as consise as follows:
@Controller
public class AccountsController {

private AccountRepository accountRepository;

@Autowired
public AccountsController(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}

@RequestMapping(method=RequestMethod.GET)
public void show(@RequestParam("number") String number, Map model)
{
model.put("account", accountRepository.findAccount(number));
}
...
The above code says:
  1. Map /accounts/show URL to AccountsController.show() method (AccountsController <-> /acccounts and show() <-> /show by convention).
  2. Parse out number request parameter and pass it as a String argument to show() method.
  3. Build the model and pass it to /WEB-INF/views/accounts/show.jsp. Here the end parts come from the config file and the middle part is a convention-based function of controller class/method names.
Neat. The gap between Grails and "raw" Spring Web MVC just got narrower.

0 comments: