Spring MVC遭遇checkbox的问题解决方式

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是首选。简单易行。

原文地址:https://www.cnblogs.com/mfrbuaa/p/5184119.html