springMVC接受前端ajax传递的数组

前端jsp代码: 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form id="addUserForm" action="${pageContext.request.contextPath}/user/addUsers" method="post">
		id:<input type="text" name="id">
		username:<input type="text" name="username">
		age:<input type="text" name="age">
		email:<input type="text" name="email">
		<button id="addUserSumbit">sumbit</button>
	</form>
</body>
<script type="text/javascript" src="${pageContext.request.contextPath}/assets/scripts/jquery.min.js"></script>
<script type="text/javascript">
	$(function() {
		$("#addUserSumbit").on("click",function(event){
			event.preventDefault();
			var id = $("#addUserForm input[name='id']").val();
			var username = $("#addUserForm input[name='username']").val();
			var age = $("#addUserForm input[name='age']").val();
			var email = $("#addUserForm input[name='email']").val();
			var user = {
				"id":id,
				"username":username,
				"age":age,
				"email":email
			}
			var users = [];
			users.push(user);
			console.log(JSON.stringify(users));
			debugger;
			var requestUrl = $("#addUserForm").prop("action");
			$.ajax({
				type:"POST",
				url:requestUrl,
				data:JSON.stringify(users),
				contentType:"application/json;charset=utf-8",
				success:function(result){
					console.log(result)
				}
				
			});
			
		});
		
		
		
	});
</script>
</html>

后端controller代码:

@Controller
@RequestMapping("/user")
public class UserController {
	//List接受数组元素为json对象,@RequestBody注解
	@RequestMapping(value="/addUsers",consumes="application/json;charset=utf-8")
	public String addUser(@RequestBody List<User> users) {
		
		System.out.println(users.size());
		return "succes";
		
	}
}

 

 

  • 0
    点赞
  • 0
    收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:技术黑板 设计师:CSDN官方博客 返回首页
评论 1
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值