In last tutorial, we have seen how to use @Path annotation at class level to get the list of all products in our sample project. Now we will see how to get particular resource from list of resources e.g. particular product if productId passed in resource uri.
As we have resource class “Product” which is mapped to uri “/products”. To get particular product, resource uri will be like “/products/{productId}”.
e.g. “/products/1” – to get product with productId = 1
First, we update our dao class to get particular product. Method "getProduct" added to return hard coded product. As mentioned, in real world, this dao class will be fetching details from database. For tutorial purpose, we have done hard coding to keep tutorial as simple as possible.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | package in.blogspot.ashish4java.invoicedetails.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import in.blogspot.ashish4java.invoicedetails.model.Product; public class ProductDao { private static Map<Integer, Product> productMap = new HashMap<Integer, Product>(); static { productMap.put(1, new Product("FirstProduct", 1)); productMap.put(2, new Product("SecondProduct", 2)); productMap.put(3, new Product("ThridProduct", 3)); productMap.put(4, new Product("FourthProduct", 4)); } public final List<Product> getAllProducts() { return new ArrayList<Product>(productMap.values()); } public final Product getProduct(final String productId) { return productMap.get(Integer.valueOf(productId)); } } |
Now, let's update resource class "ProductResource" to return details of particular product.
1 2 3 4 5 6 | @GET @Path("{productId}") public final Product getProduct(@PathParam("productId") final String productId) { final ProductDao productDao = new ProductDao(); return productDao.getProduct(productId); } |
@Path("{productId}") maps any request with uri "/products/{productId}" to this method. As already seen in previous tutorial, @GET annotation maps any incoming HTTP GET request to 'getProduct' method if it matches with @Path annotation.
Once done, deploy the changes and hit the below URL in POSTMAN (our easy to use REST client)
If response needs to be in JSON format then add "ACCEPT" request header
Examples : Which request URL calls which method of ProductResource.java
GET /webapi/products invokes "getProductList" method
GET /webapi/products/1 invokes "getProduct" method
GET /webapi/products/3 invokes "getProduct" ethodm
Another interesting thing is, even if we make getProduct method to accept int parameter, JAX-RS run time makes automatic conversion for us. So below method works too.
1 2 3 4 5 6 | @GET @Path("{productId}") public final Product getProduct(@PathParam("productId") final int productId) { final ProductDao productDao = new ProductDao(); return productDao.getProduct(""+productId); } |
This is end of tutorial. Thanks for going through this and STAY TUNED!