Java – customize webargumentresolver, such as @ pathvariable
•
Java
I want to use a custom webargumentresolver as the ID – > entity If I use the request parameter, it is simple enough: use the parameter key to determine the entity type and find it accordingly
But I want it to be like the @ pathvariable annotation
For example
http://mysite.xzy/something/enquiryId/itemId This method will be triggered
@RequestMapping(value = "/something/{enquiry}/{item}")
public String method(@Coerce Enquiry enquiry,@Coerce Item item)
@The course annotation tells webargumentresolver to use a specific service according to its type
The question is which part of the URI belongs to the entity
Someone can explain how the pathvariable annotation does this Can I use my custom annotation to simulate it
thank you.
Solution
You can use @ initbinder to let spring know how to cast a given string to your custom type
What you want is this:
@RequestMapping(value = "/something/{enquiry}")
public String method(@PathVariable Enquiry enquiry) {...}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Enquiry.class,new propertyeditorSupport() {
@Override
public String getAsText() {
return ((Enquiry) this.getValue()).toString();
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(new Enquiry(text));
}
});
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
