Search code examples
javaspringrestspring-mvchttp-request-parameters

Spring request params to accept only Integers


I am working on an spring restful endpoint which accepts page range(start & end page number). I want my request params- pageStart and pageEnd to accept only integers. When I pass 'pageStart = a' through postman I get below error:

    @RequestMapping(value = "/{accNumber}/abc/xyz", method = RequestMethod.GET)
    @Loggable
    @ResponseBody
    public RestResponse<Class1> getData(
        @Loggable @PathVariable(value = "accNumber") String accNumber,
        @RequestParam(value = "pageStart", required = false, defaultValue = "0") Integer pageStart,
        @RequestParam(value = "pageEnd", required = false, defaultValue = "10") Integer pageEnd,
        HttpServletResponse response) throws Exception {

    Class1 class1 = new Class1();
    class1 = retrieveData(accNumber, pageStart, pageEnd);
    RestResponse<Class1> restResponse = new RestResponse<Class1>(
            class1);

    return restResponse;
    }

The request is not valid [Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"a\"]

How do I handle this exception and let the user know that he should pass only integers?


Solution

  • You can handle it in two ways

    1) Using exception handler method

    Have a method in the controller

    @ExceptionHandler({Exception.class})
        public ModelAndView handleException(Exception ex) {
            ModelAndView model = new ModelAndView("Exception");
    
            model.addObject("exception", ex.getMessage());
    
            return model;
        }
    

    http://www.codejava.net/frameworks/spring/how-to-handle-exceptions-in-spring-mvc

    2) Use String parameter

    Use String as the type for all @PathVariable and @RequestParameter parameters then do the parsing inside the handler method.