2011-01-30 73 views
5

我希望客戶端和服務器應用程序使用REST服務彼此交談。我一直在試圖用Spring MVC來設計它。我期待這樣的事情:如何設計Spring MVC REST服務?

  1. 客戶端執行POST休息服務呼叫saveEmployee(employeeDTO, companyDTO)
  2. 服務器已在其控制saveEmployee(employeeDTO, companyDTO)

類似的POST方法可以這樣使用Spring MVC做了什麼?

+1

這裏看起來像一個很好的例子:http://www.stupidjavatricks.com/?p=54 – bwobbones 2011-01-30 07:24:42

+1

@bwobbones,則應將您的評論的答案;) – 2011-01-30 07:29:59

+3

@RC,不想聲稱別人的工作... – bwobbones 2011-03-21 13:32:55

回答

13

是的,這可以完成。下面是一個簡單的例子(與Spring註解)一個RESTful控制器:

@Controller 
@RequestMapping("/someresource") 
public class SomeController 
{ 
    @Autowired SomeService someService; 

    @RequestMapping(value="/{id}", method=RequestMethod.GET) 
    public String getResource(Model model, @PathVariable Integer id) 
    { 
     //get resource via someService and return to view 
    } 

    @RequestMapping(method=RequestMethod.POST) 
    public String saveResource(Model model, SomeResource someREsource) 
    { 
     //store resource via someService and return to view 
    } 

    @RequestMapping(value="/{id}", method=RequestMethod.PUT) 
    public String modifyResource(Model model, @PathVariable Integer id, SomeResource someResource) 
    { 
     //update resource with given identifier and given data via someService and return to view 
    } 

    @RequestMapping(value="/{id}", method=RequestMethod.DELETE) 
    public String deleteResource(Model model, @PathVariable Integer id) 
    { 
     //delete resource with given identifier via someService and return to view 
    } 
} 

注意,有從http請求(@RequestParam,@RequestBody,後參數的自動映射處理輸入數據的多種方式一個豆等)。爲了更長時間,也許更好的解釋和教程,嘗試谷歌搜索'rest spring mvc'(不含引號)。

客戶端(瀏覽器)-stuff通常使用JavaScript和AJAX完成,我是一個服務器後端程序員,並且不知道很多關於JavaScript的知識,但是有很多庫可用於幫助它,例如看到jQuery

參見: REST in Spring 3 MVC

1

是的,休息是很容易在使用Spring MVC實現。

@RequestMapping(value="/saveEmploee.do",method = RequestMethod.POST) 
@ResponseBody 
public void saveEmployee(@RequestBody Class myclass){ 
    //saving class. 
    //your class should be sent as JSON and will be deserialized by jackson 
    //bean which should be present in your Spring xml.  
}