spring-mvc 中抽象类的数据绑定
我已经浏览了Spring文档和源代码,但仍然没有找到我问题的答案。
我的领域模型中有这些类,并希望将它们用作spring-mvc中的支持表单对象。
public abstract class Credentials {
private Long id;
....
}
public class UserPasswordCredentials extends Credentials {
private String username;
private String password;
....
}
public class UserAccount {
private Long id;
private String name;
private Credentials credentials;
....
}
我的控制器:
@Controller
public class UserAccountController
{
@RequestMapping(value = "/saveAccount", method = RequestMethod.POST)
public @ResponseBody Long saveAccount(@Valid UserAccount account)
{
//persist in DB
return account.id;
}
@RequestMapping(value = "/listAccounts", method = RequestMethod.GET)
public String listAccounts()
{
//get all accounts from DB
return "views/list_accounts";
}
....
}
在UI上,我有不同凭据类型的动态表单。我的 POST 请求通常如下所示:
name name
credentials_type user_name
credentials.password password
credentials.username username
如果我尝试向服务器提交请求,则会引发以下异常:
org.springframework.beans.NullValueInNestedPathException: Invalid property 'credentials' of bean class [*.*.domain.UserAccount]: Could not instantiate property type [*.*.domain.Credentials] to auto-grow nested property path: java.lang.InstantiationException
org.springframework.beans.BeanWrapperImpl.newValue(BeanWrapperImpl.java:628)
我最初的想法是使用@ModelAttribute
@ModelAttribute
public PublisherAccount prepareUserAccountBean(@RequestParam("credentials_type") String credentialsType){
UserAccount userAccount = new PublisherAccount();
Class credClass = //figure out correct credentials class;
userAccount.setCredentials(BeanUtils.instantiate(credClass));
return userAccount;
}
这种方法的问题在于,在任何其他方法(如)之前调用方法也是不合适的。prepareUserAccountBean
listAccounts
一个强大的解决方案是将两者移出并移动到单独的控制器。这听起来不对:我希望所有与用户相关的操作都驻留在同一个控制器类中。prepareUserAccountBean
saveUserAccount
任何简单的解决方案?我可以以某种方式使用DataBinder,PropertyEditor或WebArgumentResolver吗?
谢谢!!!!!