How to design a Spring MVC REST service?

前端 未结 2 1249
太阳男子
太阳男子 2021-02-02 04:36

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:

2条回答
  •  星月不相逢
    2021-02-02 04:58

    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

提交回复
热议问题