调用接口时传数组到Java后台的逻辑处理
本文由 小茗同学 发表于 2016-07-30 浏览(5110)
最后修改 2017-03-01 标签:java checkbox 获取 复选框 传值 后台

如题

我们以checkbox复选框传值到后台处理为例。

假如有如下代码,页面有4个name均为pcode的复选框:

<form id="edit_form" class="form-horizontal" method="post" >
	<div class="checkbox">
		<label><input type="checkbox" name="pcode" value="blkg"/>百灵K歌</label>
		<label><input type="checkbox" name="pcode" value="ggly"/>果果乐园</label>
		<label><input type="checkbox" name="pcode" value="health"/>健身团</label>
		<label><input type="checkbox" name="pcode" value="test"/>测试后台</label>
	</div>
</form>

当提交到后台时,无论是用submit直接提交表单,还是用jQuery的$('#edit_form').serialize()都是生成类似pcode=blkg&pcode=health&pcode=test这样结构的数据(假设是GET请求)。

我们这里以SpringMVC做后台:

@RequestMapping(value="test-checkbox")
public String testCheckbox(String[] pcode)
{
	for(int i=0; i<pcode.length; i++)
	{
		System.out.print(pcode[i]+","); // 输出blkg,heath,test,
	}
	return "index.jsp";
}

如果改成这样的话:

@RequestMapping(value="test-checkbox")
public String testCheckbox(String pcode)
{
	System.out.println(pcode); // 直接输出字符串形式的“blkg,heath,test”
	return "index.jsp";
}

但是,假如我们自己获取的话:

request.getParameter("pcode"); // 只输出某一个值,如blkg
request.getParameterValues("pcode"); // 输出上面的数组

可见,SpringMVC已经帮我们把一切都封装好了。SpringMVC的处理逻辑应该是:无论何时都使用request.getParameterValues来获取,如果我们需要数组,它就以数组的形式给我们,如果我们需要字符串,它就把数组用逗号拼接之后给我们。