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"; } }
测试页面如下:
/WEB-INF/jsp/mycontroller.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>请选择</title> </head> <body> <form action="${pageContext.request.contextPath }/mycontroller.action" method="post"> <input type="checkbox" name="interest" value="a1" />a1<br /> <input type="checkbox" name="interest" value="a2" />a2<br /> <input type="checkbox" name="interest" value="a3" />a3<br /> <input type="checkbox" name="interest" value="a4" />a4<br /> <input type="checkbox" name="interest" value="a5" />a5<br /> <input type="submit"/> </form> </body> </html>
结果显示页面如下:
/WEB-INF/jsp/ok.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>操作成功</title> </head> <body> 选择的内容是:${ins}<br/> </body> </html>
结果:
字符串接收的测试代码如下(测试完数组接收后 修改即可):
@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)