Spring MVC遭遇checkbox的问题是:当checkbox全不选时候,则该checkbox域的变量为null,不能动态绑定到spring的controller方法的入参上,并抛出异常。
解决方案:
1、javascript方式提交,提交前拼提交参数串,拼完后通过ajax方式提交。可以使用controller请求参数绑定。
缺点:逐个提取表单参数,并对checkbox选项参数进行判断拼装(字符分割),最终提交到后台太麻烦。
2、添加checkbox的同名隐藏域,从而使提交过去数据永不为null。这样就可以使用controller请求参数绑定了。
1 2 3 4 |
< input type = checkbox name = test value = 1 />aaa < input type = checkbox name = test value = 2 />bbb < input type = checkbox name = test value = 3 />ccc < input type = hidden name = test /> |
提交到controller的方法:
1 2 3 4 5 6 7 |
@RequestMapping ( /test ) private String LoginAction(HttpServletRequest request,
HttpServletResponse response,
@RequestParam (value = username ) String username,
@RequestParam (value = password ) String password,
@RequestParam (value = test ) String test,
@RequestParam (value = yzm ) String yzm) { |
test参数的值为:
全不选时候:
选两个:2,3,
3、使用spring的标签,我不会用,我也不想会,因为表单很多时候都是用js写的,而非html。不希望mvc入侵太深。
综合对比:方案2是首选。简单易行。
|