How to make customEditor in Spring dynamic enough

2019-09-12 03:54发布

问题:

I have recently learned that @PathVariable cannot be validated in Spring unless we use Custom Editor.

I got the answer from the following link https://stackoverflow.com/a/28002325/1787314

but seems like all my @PathVariables would need their own class (e.g. Name.class CustomerNumber.class and so) and that will a lot of classes just for the validation.

is there a way to write a Class dynamic enough to validate based on which method is being called so for e.g. if getName is called with @PathVariable name then DynamicEditor extends PropertyEditorSupport would validate name and if @PathVariable is id then same Editor will be called but this time only id will be validated.

I hope I was able to phrase my question properly. I am new to Spring so I would really appreciate any help on this.

回答1:

At first, you can use regexp for URI to validate. Like this:

@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}")
public void handle(@PathVariable String version, @PathVariable String extension) {
    // ...
}

And I found this post, it use JSR-303 Validation with spring. But I didn't try it. I hope it can help.

[Update]

Based on the response above,the JSR-303 way seems don't work.
The solution in this post can work.

Hope it can help.