I am trying to filter products as per price range of high and low. And this is the URL i'm testing with
http://localhost:8080/webstore/products/test?high=900&low=100
This is my Repository(ProductRepository)
public interface ProductRepository {
List<Product> getProductsByPriceFilter(BigDecimal high, BigDecimal low);
}
This is my InMemoryProductRepository class which has raw data and this method
public List<Product> getProductsByPriceFilter(BigDecimal high, BigDecimal low){
List<Product> productsByPriceFilter = new ArrayList<Product>();
for(Product product : listOfProducts){
if((product.getUnitPrice().compareTo(high) < -1) && (product.getUnitPrice().compareTo(high)== 0) && (product.getUnitPrice().compareTo(low) > 1) && (product.getUnitPrice().compareTo(low)==0)){
productsByPriceFilter.add(product);
}
}
return productsByPriceFilter;
}
here is my service(ProductService)
public interface ProductService {
List<Product> getProductsByPriceFilter(BigDecimal high, BigDecimal low);
}
And here is my implementation of service(ProductServiceImpl) which consist of this method
public List<Product> getProductsByPriceFilter(BigDecimal high, BigDecimal low){
return productRepository.getProductsByPriceFilter(high, low);
}
And finally here is my ProductController
@RequestMapping("/products/test")
public String getProductsByPriceFilter(@RequestParam("high") BigDecimal high, @RequestParam("low") BigDecimal low, Model model){
model.addAttribute("product", productService.getProductsByPriceFilter(high, low));
return "products";
}
But I'm constantly getting blank page with no data of all the data i have passed in high or low. So, i guess the problem lies with my getProductsByPriceFilter method in InMemoryProductRepository class.
The problem is over here in your comparison:
if((product.getUnitPrice().compareTo(high) < -1) && (product.getUnitPrice().compareTo(high)== 0) && (product.getUnitPrice().compareTo(low) > 1) && (product.getUnitPrice().compareTo(low)==0)){
Where you can't say high
comparison result can be less than -1
and at the same time equal to zero
. Instead you need is or between two conditions or better <= 0
and the other way for low
like:
if((product.getUnitPrice().compareTo(high) <= 0) && (product.getUnitPrice().compareTo(low) >= 0))