Use @PathVariable instead of @RequestParam
Assume you have Hotels 1-500 and you would like to return result if the number is less than 500. If the Hotel Number exceeds 500 then you want to return Resource Not Found 404.
Valid URLs:
xyz.com/hotels
xyz.com/hotels/335
Invalid URL:
xyz.com/hotels/501
Define the controller as below:
@Controller
@RequestMapping("/hotels")
public class HotelController {
@RequestMapping(method=RequestMethod.GET)
public ModelAndView getHotels(){
System.out.println("Return List of Hotels");
ModelAndView model = new ModelAndView("hotel");
ArrayList<Hotel> hotels = null;
// Fetch All Hotels
model.addObject("hotels", hotels);
return model;
}
@RequestMapping(value = "/{hotelId}", method=RequestMethod.GET)
public ModelAndView getHotels(@PathVariable("hotelId") Integer hotelId){
if (hotelId > 500){
throw new ResourceNotFoundException();
}
ModelAndView model = new ModelAndView("hotel");
Hotel hotel = null;
// get Hotel
hotel = new Hotel(hotelId, "test Hotel"+hotelId);
model.addObject("hotel", hotel);
return model;
}
}
Note @RequestMapping given as /hotels, this way the getHotels() method would be invoked when the URL is
xyz.com/hotels
and the request method is GET.
If the URL contains id information like xyz.com/hotels/2 then the getHotels() with the @PathVariable would be invoked.
Now, if you want to return 404 when the hotel id is greater than 500, throw a custom Exception. Notice ResponseStatus.NOT_FOUND is annotated in the custom exception handler method below:
@ResponseStatus(value = HttpStatus.NOT_FOUND)
class ResourceNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(){
super();
}
}
@PathParamwill help you.@RequestMapping(params = "type=Hotel"). I believe it can use regular expressions as well, and accepts a single string param or an array of them.