如何使 spring MVC PathVariable 更健壮?

How can I make spring MVC PathVariable more robust?

在下面的 PathVariable 示例中:

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

如果我像 /api/100abc 那样调用此 API,将会出现数字格式异常。

有什么方法可以让id更健壮,例如:

在这两个中,我想调用/api/100

我知道我可以将路径变量的 API 参数类型从 Long 更改为 String,然后做一些逻辑来完成事情。

有没有像 AOP 或 Filter 这样的其他方法?

基于https://www.baeldung.com/spring-mvc-custom-data-binder

你可以试试:

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) {
      ....
}

是的,你可以(使路径变量“更健壮”)! ...通过实现自定义“绑定”and/or“格式化”。

Some annotated controller method arguments that represent String-based request input (such as @RequestParam, @RequestHeader, @PathVariable, @MatrixVariable, and @CookieValue) can require type conversion if the argument is declared as something other than String. For such cases, type conversion is automatically applied based on the configured converters. By default, simple types (int, long, Date, and others) are supported. You can customize type conversion through a WebDataBinder (see DataBinder) or by registering Formatters with the FormattingConversionService. See Spring Field Formatting. ...

来源:MVC|WebFlux