Exercise 23: Creating RESTFul Services - jkneal/spring-angular-train GitHub Wiki
Learn the basics of RESTFul services and how to create them using Spring MVC
-
In
edu.train.shop.shopController, create a new method named 'getProduct' that maps to the path '/products/{id}' and accepts Http Get methods. This method should take the path variable 'id' as a argument (type should be Integer). Within the method, invoke theproductRepository.findOnemethod passing the id. Return the product as a message response -
Now refactor the controller
edu.train.product.InventoryControllerto be a rest controller. To implement the methods useproductRepository. Also make the following adjustments:
- Remove the method deleteProduct
-
addProductsshould accept Http Put methods, and after adding the product return all products -
searchProductsshould invoke the methodproductRepository.findByNameMatching -
deleteProductByIdshould map to the path '/inventory/{id}' and accept Http Delete methods. This method should also returnResponseEntity<Void>. Within the method, first check if the id given is a valid product (by using the productRepository). If the id is not valid, return the Http status code 404. Otherwise carry out the deletion and return 200
- Start the training application and go to the app home page
- Click on the link 'Ex 23 Get Product'. Verify the the JSON for product with id 1 is returned
- Now go back to the menu and click on the link 'Ex 23 Get All'. Verify the JSON for all five products is returned.
- Now go back to the menu and click on the link 'Ex 23 Add'. Verify you receive an alert with the message "Product added successfully"
- Now click on the link 'Ex 23 Search'. Verify the JSON for products with names "Baseball" and "Basketball" is returned (with the products in that order)
- Now go back to the menu and click on the link 'Ex 23 Delete'. Verify you receive an alert with the message "Product deleted successfully"
- Now click on the link 'Ex 23 Delete Invalid'. Verify you receive an alert with the message "Error in request: status code: 404"