Spring Rest

springmvc

To implement a REST service that returns JSON:

Add the Jackson library as a dependency
Create a controller class and add the @RestController annotation to the class
You controller method should return a list of model instances instead of a string.

@RestController
public class TodoRestController {
    @Autowired
    private TodoService service;

    @RequestMapping(value = "/todo/", method = RequestMethod.GET)
    public List<Todo> listAllTodos() {
        List<Todo> todos = service.retrieveTodos("username");
        return todos;
    }
}

To use the URL mapping: /todo/{id} and the @PathVariable annotation:

@RestController
public class TodoRestController {
    @Autowired
    private TodoService service;

    @RequestMapping(value = "/todo/", method = RequestMethod.GET)
    public List<Todo> listAllTodos() {
        List<Todo> users = service.retrieveTodos("username");
        return users;
    }

    @RequestMapping(value = "/todo/{id}", method = RequestMethod.GET)
    public Todo retrieveTodo(@PathVariable("id") int id) {
        return service.retrieveTodo(id);
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License