Search code examples
springspring-bootspring-mvcspring-restpath-variables

How can I make spring MVC PathVariable more robust?


In PathVariable example below:

@GetMapping("/{id}")
SomeReturn get(@PathVariable Long id)
{
      ....
}

If I call this API like /api/100abc, will get a number format exception.

Is there any way to make id more robust, for example:

  • /api/100
  • /api/100abc

In both of them, I'd like to call /api/100.

I know I can change the API parameter type of path variable from Long to String, and do some logic to make things done.

Is there any other way like AOP or Filter to do so?


Solution

  • Based on https://www.baeldung.com/spring-mvc-custom-data-binder

    You can try :

    public class RobustId {
        private Long id;
    
        public RobustId(Long id) {
            this.id = id;
        }
    
        // getters and setters below...
    }
    
    public class RobustIdConverter implements Converter<String, RobustId> {
    
        @Override
        public RobustId convert(String from) {
            Long id = null;
    
            for (int i=0; i<from.length(); i++) {
                char c = from.charAt(i);
                if ( !Character.isDigit(c) ) {
                    id = Long.parseLong(from.substring(0, i));
                    break;
                }
            }
            return new RobustId(id);
        }
    }
    
    @GetMapping("/{id}")
    SomeReturn get(@PathVariable RobustId id) {
          ....
    }