簡體   English   中英

如何設計Spring MVC REST服務?

[英]How to design a Spring MVC REST service?

我希望客戶端和服務器應用程序使用REST服務相互通信。 我一直在嘗試使用Spring MVC來設計它。 我正在尋找這樣的東西:

  1. 客戶端執行POST休息服務調用saveEmployee(employeeDTO, companyDTO)
  2. Server在其控制器saveEmployee(employeeDTO, companyDTO)有類似的POST方法

可以使用Spring MVC完成嗎?

是的,這可以做到。 這是一個RESTful Controller的簡單示例(使用Spring注釋):

@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-request的傳入數據(@RequestParam,@ RequestBody,自動映射后參數到bean等)。 對於更長和可能更好的解釋和教程,嘗試谷歌搜索'rest spring mvc'(沒有引號)。

通常客戶端(瀏覽器)-stuff是用JavaScript和AJAX完成的,我是一個服務器后端程序員,並且對JavaScript知之甚少,但是有很多庫可以幫助它,例如參見jQuery

另請參見: Spring 3 MVC中的REST

是的,使用spring MVC很容易實現Rest。

@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.      
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM