SpringMVC接收checkbox传值

时间:2020-02-28 16:37:09 类型:JAVA
字号:    

  SpringMVC接收checkbox传值

  Controller方法形参接收checkbox的值,既可以用String,也可以用String[]。


  字符串数组接收的测试代码如下:

@Controller
@RequestMapping("/mycontroller")
public class MyController {

    @RequestMapping(method = RequestMethod.GET)
    public String form() {
        return "mycontroller";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String form1(@RequestParam("interest") String[] interest, Model model) {
        String a = Arrays.toString(interest);
        model.addAttribute("ins", a);
return "ok";
    }

}

  字符串接收的测试代码如下(测试完数组接收后 修改即可):

@Controller
@RequestMapping("/mycontroller")
public class MyController {

    @RequestMapping(method = RequestMethod.GET)
    public String form() {
        return "mycontroller";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String form1(@RequestParam("interest") String interest, Model model) {
        model.addAttribute("ins", interest);
        
        return "ok";
    }

}

  小知识:

  如果checkbox都留空(不选择),那么Controller会报错。解决办法:①前端js判断;②前端加一个hidden的checkbox。

  补充方法:

  @RequestParam(value = "interest", required = false)


<