Tuesday, February 3, 2015

Developing a simple Rest service using spring 4

@RestController annotation which marks the class as a controller where every method returns Domain Object instead of a view.

@RestController
public class RestTestController {

    @RequestMapping("/sayHello")
    public Greeting sayHello(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(name);
    }
}

The above rest controller URL: http://localhost:8080/sayHello?name=Kiran

where as Request mapping has URL:sayHello and its accepting a parameter named name and the return type of this method is Object as said earlier all the methods inside a @RestController will return the domain object istead of view. The return type will automatically converted into JSON object.

This Greeting object contain a setter and getter method of name.

In the case of @Controller annotation you need to manually specify the @ResponseBody annotation to controller specifying and object is returning instead of a view.

No comments: