Fork me on GitHub

Programming Design Notes

Spring Web MVC - REST

| Comments

在 Spring Framework 幫助下,很容易便可以做出 REST 風格的 URL。
REST 的介紹: Representational State Transfer

REST 風格的 URL 會長成以下的樣子:
http://pro.ctlok.com/2010/06/28/bababa

各位是否覺得很熟悉? 經常瀏覽不同類型的 Blog 的朋友應該見慣這種 URL 吧,在 WordPress 也可以將文章 URL 設定為這種格式,是對搜尋器優化了的一種 URL。在 Spring Web MVC 也可以做到 REST 風格的 URL,而且很簡單。

在這裡我不把 Spring Web MVC 重頭說一次了,有興趣的請在我的部落格找找 Spring 相關的文章。

在這裡我跟以上的 URL 做一個示範:
@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";
}

就是這麼簡單就做到了,如果是以前不懂這種技術,可能會這麼做:
http://www.abcxyz.com/post?year=2010&month=06&day=28&title=bababa

這樣雖然也可以達到相同目的,但這種 URL 不利於搜尋器。

Spring 亦可以將參數自動轉換成其他格式:
@RequestMapping(value="/user/{userId}", method=RequestMethod.GET)
public String findPost(@PathVariable("userID") long userID, Model model) {
//........
}

在已註冊的 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) {
//........
}

亦可以將數據綁定在參數上:
@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) {
//........
}

相關書籍: Expert Spring MVC and Web FlowExpert Spring MVC and Web FlowSpring in Action