How to design a Spring MVC REST service?

2019-03-10 10:51发布

问题:

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:

  1. Client does a POST rest service call saveEmployee(employeeDTO, companyDTO)
  2. Server has a similar POST method in its controller saveEmployee(employeeDTO, companyDTO)

Can this be done using Spring MVC?

回答1:

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

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).

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

See also: REST in Spring 3 MVC



回答2:

Yes, Rest is very easy to implement using 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.      
}