如何设计Spring MVC REST服务?
问题内容:
我希望客户端和服务器应用程序可以使用REST服务相互通信。我一直在尝试使用Spring MVC进行设计。我正在寻找这样的东西:
- 客户端进行POST休息服务呼叫
saveEmployee(employeeDTO, companyDTO)
- 服务器在其控制器中具有类似的POST方法
saveEmployee(employeeDTO, companyDTO)
可以使用Spring MVC完成吗?
问题答案:
是的,可以这样做。这是RESTful控制器的一个简单示例(带有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请求的传入数据(@ RequestParam,@
RequestBody,后参数到Bean的自动映射等)。有关更长或更可能更好的解释和教程,请尝试使用谷歌搜索“ rest spring
mvc”之类的东西(不带引号)。
通常,客户端(浏览器)的工作是通过JavaScript和AJAX完成的,我是服务器后端程序员,对JavaScript并不了解很多,但是有很多可用的库来帮助它,例如,请参见jQuery。
另请参阅: Spring 3 MVC中的REST