如何设计Spring MVC REST服务? [英] How to design a Spring MVC REST service?
问题描述
我希望客户端和服务器应用程序使用REST服务相互通信。我一直在尝试使用Spring MVC来设计它。我正在寻找这样的东西:
I want the client and server application to talk to each other using REST services. I have been trying to design this using Spring MVC. I am looking for something like this:
- 客户端进行POST休息服务调用
saveEmployee(employeeDTO,companyDTO)
- 服务器在其控制器中有类似的POST方法
saveEmployee(employeeDTO,companyDTO)
- Client does a POST rest service call
saveEmployee(employeeDTO, companyDTO)
- Server has a similar POST method in its controller
saveEmployee(employeeDTO, companyDTO)
这可以使用Spring MVC完成吗?
Can this be done using Spring MVC?
推荐答案
是的,这可以做到。这是RESTful Controller的一个简单示例(带有Spring注释):
Yes, this can be done. Here's a simple example (with Spring annotations) of a RESTful Controller:
@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'(不带引号)。
Note that there are multiple ways of handling the incoming data from http-request (@RequestParam, @RequestBody, automatic mapping of post-parameters to a bean etc.). For longer and probably better explanations and tutorials, try googling for something like 'rest spring mvc' (without quotes).
通常客户端(浏览器)-stuff完成JavaScript和AJAX,我是服务器后端程序员,并不了解很多JavaScript,但有很多库可以帮助它,例如参见 jQuery
Usually the clientside (browser) -stuff is done with JavaScript and AJAX, I'm a server-backend programmer and don't know lots about JavaScript, but there are lots of libraries available to help with it, for example see jQuery
这篇关于如何设计Spring MVC REST服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!