Sunday, 4 March 2018

@RequestMapping vs. GetMapping


@RequestMapping is generic annotation which can define path mapping with request methods (GET/POST/PUT/DELETE etc.)

It can be applied to class and methods.
By default request method will be GET.

EXAMPLE

@Component
@RequestMapping("emp")public class EmpController {

   
   
@RequestMapping("hello")
    @ResponseBody

    public String hello() {
        return "Hello !";
    }
}

Calling URL http://localhost:8080/emp/hello will call hello method.

To define request method and path together with @RequestMapping :
@RequestMapping(path="hello", method=RequestMethod.GET)





Apart from @RequestMapping, there are several annotations specific to each request method :
  • @GetMapping
  • @PostMapping
  • @PutMapping
etc.


EXAMPLE
When exposing REST APIs, single @RequestMapping can indicate main verb and multiple methods using different annotations can indicate different operations like, get all records, get by ID, save, update etc.

@Component
@RequestMapping("emp")
public class EmpController {


    @Resource
    private EmployeeRepository employeeRepository;


    @GetMapping
    public ResponseEntity<List<Employee>> getAllEmp() {
        return ResponseEntity.ok((List<Employee>) employeeRepository.findAll());
    }

   
    @GetMapping("{id}")
    public ResponseEntity<Employee> emp(@PathVariable long id) {
        return ResponseEntity.ok(employeeRepository.findOne(id));
    }

   
    @PostMapping
    public ResponseEntity<Employee> emp(@RequestBody Employee emp) {
        return ResponseEntity.ok(employeeRepository.save(emp));
    }

   
    @PutMapping
    public ResponseEntity<Employee> emp(@PathVariable long id, @Valid @RequestBody Employee emp) {
        return ResponseEntity.ok(employeeRepository.save(emp));
    }

}


Different URLs can be used for different operations :
GET http://localhost:8080/emp

POST http://localhost:8080/emp
Request Body = { "name" : "shaan", "salary" : 12 }
Header = Content-Type : application/json


No comments:

Post a Comment

Note: only a member of this blog may post a comment.