一、背景

  最近在做一些东西的时候,遇到一个需要Springmvc后台接收list类型数据的需求,几经辗转才完美解决了这个问题,今天记下来方便以后使用,也分享给需要的小伙伴们~

二、实现方式

实现方式一

前端页面

 <%@ 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>测试</title>
</head>
<body>
<input type="button" name="request" value="请求后台" style="width:200px;height:50px;background-color:red;margin-bottom:20px;">
<div name="rs"></div>
<input type="checkbox" name="se" value="1">hafiz.zhang<br/>
<input type="checkbox" name="se" value="2">jack.chen<br/>
<input type="checkbox" name="se" value="3">lili.wang<br/>
<script type="text/javascript"> $("input[name='request']").click(function(){
var data = [];
$("input[name='se']").each(function(){
if($(this).prop("checked")) {
data.push($(this).val());
}
});
var json_data = JSON.stringify(data);
$.ajax({
type:"post",
url:$.wap.url + "/test/index",
contentType:"application/json",
data:json_data ,
dataType:"json",
success:function(data){
var str="";
for(var i = 0; i < data.length; i++) {
str += ";name=" + data[i];
}
$("div[name='rs']").html(str);
},
error:function(){
alert("出错啦");
}
});
});
</script>
</body>
</html>

后台接收

 package com.hafiz.www.controller;

 import java.util.ArrayList;
import java.util.List; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(value = "/index", method = RequestMethod.POST)
@ResponseBody
public List<Integer> test(@RequestBody ArrayList<Integer> ids){
System.out.println("List==" + ids);
return ids;
}
}

注意:这种方法只适用于POST方法提交,(上面代码中标红的是必不可少的代码)如果使用get方法会出现如下图所示的错误

这是因为get方式的参数中的双引号会被编码,导致传到后台的不再是json串格式,所以解析出错。

实现方式二

前端页面

 <%@ 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>测试</title>
</head>
<body>
<input type="button" name="request" value="请求后台" style="width:200px;height:50px;background-color:red;margin-bottom:20px;">
<div name="rs"></div>
<input type="checkbox" name="se" value="1">hafiz.zhang<br/>
<input type="checkbox" name="se" value="2">jack.chen<br/>
<input type="checkbox" name="se" value="3">lili.wang<br/>
<script type="text/javascript"> $("input[name='request']").click(function(){
var data = [];
$("input[name='se']").each(function(){
if($(this).prop("checked")) {
data.push($(this).val());
}
});
$.ajax({
type:"get",
url:$.wap.url + "/test/index",
data:{"datas":data},//或者data:{"datas[]":data}
dataType:"json",
success:function(data){
var str="";
for(var i = 0; i < data.length; i++) {
str += ";name=" + data[i];
}
$("div[name='rs']").html(str);
},
error:function(){
alert("出错啦");
}
});
});
</script>
</body>
</html>

后台接收,指定参数名必须以数组方式,如:@RequestParam("datas[]")

  1).通过ArrayList接收

 package com.hafiz.www.controller;

 import java.util.ArrayList;
import java.util.List; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(value = "/index", method = RequestMethod.GET)
@ResponseBody
public List test(@RequestParam("datas[]") ArrayList<Integer> ids){
System.out.println("List==" + ids);
return ids;
}
}

  2).通过数组进行接收

 package com.hafiz.www.controller;

 import java.util.ArrayList;
import java.util.List; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(value = "/index", method = RequestMethod.POST)
@ResponseBody
public Integer[] test(@RequestParam("datas[]") Integer[] ids){
System.out.println("ids==" + ids);
return ids;
}
}

注意:

  1.这种方式对于get和post方式的请求同样都适用....

  2.以上两种实现方式传到后台的数据不能为null,否则会报Http 400错误。

实现方式三

 前端页面

 <%@ 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>测试</title>
</head>
<body>
<input type="button" name="request" value="请求后台"
style="width:200px;height:50px;background-color:red;margin-bottom:20px;">
<div name="rs"></div>
<input type="checkbox" name="se" value="1">hafiz.zhang<br/>
<input type="checkbox" name="se" value="2">jack.chen<br/>
<input type="checkbox" name="se" value="3">lili.wang<br/>
<script type="application/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript"> $("input[name='request']").click(function () {
var data = [];
$("input[name='se']").each(function () {
if ($(this).prop("checked")) {
data.push($(this).val());
}
});
$.ajax({
type: "post",
url: "/test/index",
data: {"datas": data.join()}
dataType: "json",
success: function (data) {
var str = "";
for (var i = 0; i < data.length; i++) {
str += ";name=" + data[i];
}
$("div[name='rs']").html(str);
},
error: function () {
alert("出错啦");
}
});
});
</script>
</body>
</html>

后端代码

  1)通过数组接收

 package com.hafiz.www.controller;

 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList;
import java.util.List; /**
* Desc:测试控制器
* Created by hafiz.zhang on 2017/7/2.
*/
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(value = "/index", method = RequestMethod.POST)
@ResponseBody
public Integer[] test(@RequestParam("datas") Integer[] ids) {
System.out.println("ids=" + ids);
return ids;
}
}

  2).通过List接收

package com.hafiz.www.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List; /**
* Desc:测试控制器
* Created by hafiz.zhang on 2017/7/2.
*/
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(value = "/index", method = RequestMethod.POST)
@ResponseBody
public List test(@RequestParam("datas") List<Integer> ids) {
System.out.println("ids=" + ids);
return ids;
}
}

这种方式即使没有选中任何复选框进行提交,也不会报错!

对于想要前端传自定义对象数组到后端,以上的方式就不适用了,那么解决办法是什么呢?

  • ajax请求中设置contentType:"application/json;charset=utf-8"

  • ajax请求中设置data:JSON.stringify(dataList)

  • 后端Controller种用@RequestBody YourObject[] data进行接收,并且只能用数组接收.

如果你有更好的实现方式,希望可以拿来分享。。。。

三、总结

1.实现方式一只对post方法有效,且比较繁琐,不推荐!

2.实现方式二要求后端接收的时候必须声明参数为数组,但可以使用数组或者list进行接收参数,如:@RequestParam("datas[]"),前端使用data:{"datas":data}或data:{"datas[]":data}都可以!且post和get方法都适用。但是不能传空数组,限制也比较多,也不太推荐。

3.实现方式三只需要前端传值的时候使用数组的join()方法,为空数组也不会报错,配置简单,要求少,且支持使用数组和list进行接收参数,比较推荐!

关于传递自定义对象的集合,可以参考这篇文章:https://blog.csdn.net/sweetgirl520/article/details/79127223

SpringMVC后台接收list类型的数据的实现方式的更多相关文章

  1. .net mvc前台如何接收和解析后台的字典类型的数据 二分搜索算法 window.onunload中使用HTTP请求 网页关闭 OpenCvSharp尝试 简单爬虫

    .net mvc前台如何接收和解析后台的字典类型的数据   很久没有写博客了,最近做了一个公司门户网站的小项目,其中接触到了一些我不会的知识点,今日事情少,便记录一下,当时想在网上搜索相关的内容,但是 ...

  2. SpringBoot后台接收前台的字符串数据

    需求 将前台传入的字符串数据转为int类型. 操作 在pom.xml中添加引用. <dependency> <groupId>org.apache.commons</gr ...

  3. springMVC怎么接收日期类型的参数?

    springMVC怎么接收日期类型的参数? springMVC的controller中用实体接受页面传递的参数,并且实体中的属性类型为日期类型,怎么接收呢?如果接收不到会进不到controller中. ...

  4. js进阶 14-3 如何接收load函数从后台接收到的返回数据

    js进阶 14-3 如何接收load函数从后台接收到的返回数据 一.总结 一句话总结:load方法的回调函数的参数即可接收从后台的返回数据. 1.load方法的回调函数的参数是什么? 语法:load( ...

  5. springMVC参数绑定JSON类型的数据

    需求就是: 现在保存一个Student,并且保存Student的friend,一个student会有多个朋友,这里要传递到后台的参数是: var friends = new Array(); var ...

  6. angular的post请求,SpringMVC后台接收不到参数值的解决方案

    这是我后台SpringMVC控制器接收isform参数的方法,只是简单的打出它的值: @RequestMapping(method = RequestMethod.POST) @ResponseBod ...

  7. 解决angular的post请求后SpringMVC后台接收不到参数值问题的方法

    这是我后台SpringMVC控制器接收isform参数的方法,只是简单的打出它的值: @RequestMapping(method = RequestMethod.POST) @ResponseBod ...

  8. .net mvc前台如何接收和解析后台的字典类型的数据

    很久没有写博客了,最近做了一个公司门户网站的小项目,其中接触到了一些我不会的知识点,今日事情少,便记录一下,当时想在网上搜索相关的内容,但是没有找到. 今天想记录一下这样一个小的需求的做法.先说一下我 ...

  9. springmvc接收JSON类型的数据

    1.在使用AJAX传递JSON数据的时候要将contentType的类型设置为"application/json",否则的话会提示415错误 2.传递的data需要时JSON类型的 ...

随机推荐

  1. Spring拦截机制之后端国际化心得

    需求 前端请求的header里带有Prefer_Lang参数,向后端传递国际化信息,后端需要在处理业务之前(建立拦截机制),将Prefer_Lang保存于线程上下文. 思路分析 初次接收该需求时,为了 ...

  2. SOA 实现:服务设计原则

    http://www.ibm.com/developerworks/cn/webservices/ws-soa-design/ 引言 面向服务的体系结构(Service-Oriented Archit ...

  3. Spring--开山篇

    ·Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建.简单来说,Spring是一个分层的JavaSE/EEfull-stack( ...

  4. Java学习笔记之方法重载

    被重载的方法必须具有不同的参数列表.不能基于不同修饰符或返回值类型来重载方法. package welcome; public class TestMethodOverloading { public ...

  5. Nginx 和 IIS 实现动静分离

    前段时间,搞Nginx+IIS的负载均衡,想了解的朋友,可以看这篇文章:<nginx 和 IIS 实现负载均衡>,然后也就顺便研究了Nginx + IIS 实现动静分离.所以,一起总结出来 ...

  6. 关于ajax请求,在参数中添加时间戳的必要性

    之前做项目的时候,看到别人的前端ajax请求代码中,都会带有一个时间戳类型的参数,当时随便查了一下,是为了防止浏览器缓存的原因,所以也没有进行深究,每次写的时候也习惯性的带一个,最近新项目中,我发现好 ...

  7. Java集合之LinkedList

    一.LinkedList概述 1.初识LinkedList 上一篇中讲解了ArrayList,本篇文章讲解一下LinkedList的实现. LinkedList是基于链表实现的,所以先讲解一下什么是链 ...

  8. CSS布局奇淫技巧之--各种居中

    居中是我们使用css来布局时常遇到的情况.使用css来进行居中时,有时一个属性就能搞定,有时则需要一定的技巧才能兼容到所有浏览器,本文就居中的一些常用方法做个简单的介绍. 注:本文所讲方法除了特别说明 ...

  9. 欢迎来到Joyful Physics博客

    本博客主要包括以下内容: 物理课程 预计会涵盖非物理专业普通物理.物理专业普通物理.理论物理(四大力学).凝聚态物理,会特别关注软物质物理,因为博主是做软物质物理的. 软硬科普 软科普写给非专业人士. ...

  10. Spring_的jar详细说明

    org.springframework.aop ——Spring的面向切面编程,提供AOP(面向切面编程)的实现 org.springframework.asm——spring 2.5.6的时候需要a ...