Simple and short question: Is there a way to create a handler for custom @RequestParam types in Spring MVC?
I know I can register custom WebArgumentResolver
s but then I cannot bind these to parameters. Let me describe my use case:
Consider I have defined a Model Class Account
:
public class Account {
private int id;
private String name;
private String email;
}
My request handling method looks as follows:
@RequestMapping("/mycontroller")
public void test(Account account1, Account account2) {
//...
}
If I make a request mydomain.com/mycontroller?account1=23&account2=12 I would like to automatically load the Account objects from the database and return an error if they dont exist.
Yes, you should just register a custom property editor:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(CustomType.class,
new CustomTypePropertyEditor());
}
Update: Since you need to access the DAO, you need the property editor as a spring bean. Something like:
@Component
public class AccountPropertyEditor extends PropertyEditorSupport {
@Inject
private AccountDAO accountDao;
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(accountDao.getById(Integer.parseInt(text)));
}
@Override
public String getAsText() {
return String.valueOf(((Account) getValue()).getId());
}
}
And then, when registering the editor, get the editor via injection rather than instantiating it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.