Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design a Spring MVC REST service?

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?

like image 226
outvir Avatar asked Jan 30 '11 06:01

outvir


People also ask

Can we use RestController in Spring MVC?

Spring RestController annotation is used to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the defined request handler method. Once response body is generated from the handler method, it converts it to JSON or XML response.


1 Answers

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

like image 170
esaj Avatar answered Oct 04 '22 03:10

esaj