폼데이터
<form action="/process.do" method="post" name="testForm">
<input type="text" name="name" value="홍철수">
<input type="text" name="name" value="김철수">
<input type="text" name="name" value="이철수">
</form>
위와같은 데이터를 Controller에서 받을 경우
@Controller
public class TestController {
@RequestMapping(value = "/process.do")
public String testMethod(HttpServletRequest request, Model model) {
String[] arrayParam = request.getParameterValues("name");
for (int i = 0; i < arrayParam.length; i++) {
System.out.println(arrayParam[i]);
}
return "view.jsp";
}
}
단 특이한 것은 Ajax로 전송할 때 get parameter 형태(?name=홍철수&name=김철수&name=이철수)가 아닌 Object의 배열 형태({ name : [ "홍길동", "김철수", "이영희" ] })로 전송하면 controller에서 전송받은 데이터의 parameter name에 자동으로 배열표시'[ ]'가 붙는다.
Ajax방식을 사용하여 배열로 전송
<script>
var formData = {
"name": [ "홍철수", "김철수", "이철수" ];
};
$.ajax({
type: "post",
url: "/process.do",
dataType: "json",
data: formData,
success: function (data) {
}
});
</script>
Ajax방식을 사용하여 Object의 배열로 전송 받은 controller
@Controller
public class TestController {
@RequestMapping(value = "/process.do")
public String testMethod(HttpServletRequest request, Model model) {
String[] arrayParam = request.getParameterValues("name[]");
for (int i = 0; i < arrayParam.length; i++) {
System.out.println(arrayParam[i]);
}
return "view.jsp";
}
}