Spring REST 6: CRUD

Annotations

@RestController

The @RestController annotation was introduced in Spring 4.0 to simplify the creation of RESTful web services. It’s a convenience annotation that combines @Controller and @ResponseBody – which eliminates the need to annotate every request handling method of the controller class with the @ResponseBody annotation.

@PathVariable

While @RequestParams extract values from the query string, @PathVariables extract values from the URI path:

1
2
3
4
5
@GetMapping("/foos/{id}")
@ResponseBody
public String getFooById(@PathVariable String id) {
return "ID: " + id;
}

For @PathVariable, we map on path:

1
2
3
http://localhost:8080/foos/abc
----
ID: abc

1
2
3
4
5
@GetMapping("/foos")
@ResponseBody
public String getFooByIdUsingQueryParam(@RequestParam String id) {
return "ID: " + id;
}

For @RequestParam, we map on path:

1
2
3
http://localhost:8080/foos?id=abc
----
ID: abc

@RequestBody

Simply put, the @RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object.

CRUD

POST

1
2
3
4
5
6
7
    @PostMapping("/saveCustomer")
public Customer saveCustomer(@RequestBody Customer theCustomer) {
// save the customer using our service
theCustomer.setId(0);
customerService.saveCustomer(theCustomer);
return theCustomer;
}

GET

1
2
3
4
5
6
@GetMapping("/search/{theSearchName}")
public List<Customer> search(@PathVariable String theSearchName) {
// search customers from the service
List<Customer> theCustomers = customerService.searchCustomers(theSearchName);
return theCustomers;
}

DELETE

1
2
3
4
5
6
    @DeleteMapping("/delete/{customerId}")
public String delete(@PathVariable int customerId) {
// Customer tempCustomer = customerService.getCustomer(customerId);
customerService.delete(customerId);
return "Delete customer id:" + customerId;
}

PUT

1
2
3
4
5
@PutMapping("/updateCustomer")
public Customer updateCustomer(@RequestBody Customer theCustomer) {
customerService.saveCustomer(theCustomer);
return theCustomer;
}

Test

For get/delete testing, just input the uri and select the right method.
For put/post testing, besides the steps above:

  • Select ‘Body’
  • Select ‘raw’
  • Select ‘JSON’
  • Input data in JSON fashion
  • Send request