Uncategorized

Spring Web MVC – REST

Spring Web MVC - REST

In Spring Web MVC, I can easily to develop below URL.

REST style URL:

http://www.open-tutoial.com/2010/06/28/bababa

Yes! This is a WordPress Post’s URL. REST style URL is a search engine optimized URL. Many WEB application also using this style url. Using Spring Web MVC, I can easily to develop REST style application.
About REST: Representational State Transfer


For instance, Spring WEB MVC Controller implement REST:

@RequestMapping(value = "/{year}/{month}/{day}/{postTitle}", method = RequestMethod.GET)
public String findPost(@PathVariable("year") String year,
@PathVariable("month") String month,
@PathVariable("day") String day,
@PathVariable("postTitle") String postTitle, Model model) {
Post post = postService.find(year, month, day, postTitle);
model.addAttribute("post", post);
return "post";
}

This method implement REST. Result is same as a top URL.

Long time ago, we implement same function may be do that:

http://www.abcxyz.com/post?year=2010&month=06&day=28&title=bababa

However, it can make a same result, but not a search engine optimized URL.

Spring can auto transform parameter to some format:

@RequestMapping(value="/user/{userId}", method=RequestMethod.GET)
public String findPost(@PathVariable("userID") long userID, Model model) {
//........
}

You can add parameter at registered URI:

@RequestMapping(value="/user/{userId}", method=RequestMethod.GET)
public String findPost(@PathVariable("userID") long userID, Model model) {
//........
}

@RequestMapping(value="/user/*/friend/{friendID}", method=RequestMethod.GET)
public String findPost(@PathVariable("friendID") long friendID, Model model) {
//........
}

Spring data binding:

@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}

@RequestMapping(value="/{date}/{postTitle}", method=RequestMethod.GET)
public String findPost(@PathVariable("date") Date date, @PathVariable("postTitle") String postTitle, Model model) {
//........
}