您好,欢迎访问一九零五行业门户网

SpringMVC如何解决同名参数绑定问题

这篇文章主要介绍了springmvc如何解决同名参数绑定问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
比如,我的表单是这样的:
<form action="/test.action" method="post">  
   <input name="user.name">  
   <input name="acc.name">  
   <input type="submit">  
</form>

如果是sturts的话,这个很好解决,在controller声明user和acc对象就行了,但是springmvc的参数绑定和struts不一样,它会自动的去找对应的属性绑定,而如果你的action是这样的:
@requestmapping(/test.action)
public void test(account account, user user){
   system.out.println(user);
   system.out.println(account);
}

这样的话是会报错的,怎么办呢?
这里要用到@initbinder这个注解,详细的解释可以找相关资料,这里只讲怎么用。在controller类添加下面两个方法,作用是把指定的开头标识符的值赋给成指定名字的对象
@initbinder(account)  
public void initaccountbinder(webdatabinder binder) {  
   binder.setfielddefaultprefix(acc.);  
}
@initbinder(user)  
public void inituserbinder(webdatabinder binder) {  
   binder.setfielddefaultprefix(user.);  
}

然后把action方法改造成下面这样就可以了。
@requestmapping(/test.action)
public void test(@modelattribute(account) account account, @modelattribute(user) user user){
   system.out.println(user);
   system.out.println(account);
}

注意@modelattribute里面的参数要跟上面定义的@initbinder里面的值对应,否则是取不到值的。
相关推荐:
springmvc对象绑定参数重名解决
spring mvc 不同对象的同名参数绑定
关于springmvc pojo参数绑定“不成功”的一个原因
以上就是springmvc如何解决同名参数绑定问题的详细内容。
其它类似信息

推荐信息