SpringMVC后台接收list类型的数据的实现方式

一、背景

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

二、实现方式

实现方式一

前端页面

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>测试</title>
 8 </head>
 9 <body>
10     <input type="button" name="request" value="请求后台" style="width:200px;height:50px;background-color:red;margin-bottom:20px;">
11     <div name="rs"></div>
12     <input type="checkbox" name="se" value="1">hafiz.zhang<br/>
13     <input type="checkbox" name="se" value="2">jack.chen<br/>
14     <input type="checkbox" name="se" value="3">lili.wang<br/>
15 <script type="text/javascript">
16 
17     $("input[name='request']").click(function(){
18         var data = [];
19         $("input[name='se']").each(function(){
20             if($(this).prop("checked")) {
21                 data.push($(this).val());
22             }
23         });
24         var json_data = JSON.stringify(data);
25         $.ajax({
26             type:"post",
27             url:$.wap.url + "/test/index",
28             contentType:"application/json",
29             data:json_data ,
30             dataType:"json",
31             success:function(data){
32                 var str="";
33                 for(var i = 0; i < data.length; i++) {
34                     str += ";name=" + data[i];
35                 }
36                 $("div[name='rs']").html(str);
37             },
38             error:function(){
39                 alert("出错啦");
40             }
41         });
42     });    
43 </script>
44 </body>
45 </html>

后台接收

 1 package com.hafiz.www.controller;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.RequestBody;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.RequestMethod;
10 import org.springframework.web.bind.annotation.ResponseBody;
11 
12 @Controller
13 @RequestMapping("/test")
14 public class TestController {
15     @RequestMapping(value = "/index", method = RequestMethod.POST)
16     @ResponseBody
17     public List<Integer> test(@RequestBody ArrayList<Integer> ids){
18         System.out.println("List==" + ids);
19         return ids;
20     }
21 }

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

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

实现方式二

 前端页面

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>测试</title>
 8 </head>
 9 <body>
10     <input type="button" name="request" value="请求后台" style="width:200px;height:50px;background-color:red;margin-bottom:20px;">
11     <div name="rs"></div>
12     <input type="checkbox" name="se" value="1">hafiz.zhang<br/>
13     <input type="checkbox" name="se" value="2">jack.chen<br/>
14     <input type="checkbox" name="se" value="3">lili.wang<br/>
15 <script type="text/javascript">
16 
17     $("input[name='request']").click(function(){
18         var data = [];
19         $("input[name='se']").each(function(){
20             if($(this).prop("checked")) {
21                 data.push($(this).val());
22             }
23         });
24         $.ajax({
25             type:"get",
26             url:$.wap.url + "/test/index",
27             data:{"datas":data},//或者data:{"datas[]":data}
28             dataType:"json",
29             success:function(data){
30                 var str="";
31                 for(var i = 0; i < data.length; i++) {
32                     str += ";name=" + data[i];
33                 }
34                 $("div[name='rs']").html(str);
35             },
36             error:function(){
37                 alert("出错啦");
38             }
39         });
40     });    
41 </script>
42 </body>
43 </html>

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

  1).通过ArrayList接收

 1 package com.hafiz.www.controller;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RequestMethod;
 9 import org.springframework.web.bind.annotation.RequestParam;
10 import org.springframework.web.bind.annotation.ResponseBody;
11 
12 @Controller
13 @RequestMapping("/test")
14 public class TestController {
15     @RequestMapping(value = "/index", method = RequestMethod.GET)
16     @ResponseBody
17     public List test(@RequestParam("datas[]") ArrayList<Integer> ids){
18         System.out.println("List==" + ids);
19         return ids;
20     }
21 }

  2).通过数组进行接收

 1 package com.hafiz.www.controller;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RequestMethod;
 9 import org.springframework.web.bind.annotation.RequestParam;
10 import org.springframework.web.bind.annotation.ResponseBody;
11 
12 @Controller
13 @RequestMapping("/test")
14 public class TestController {
15     @RequestMapping(value = "/index", method = RequestMethod.POST)
16     @ResponseBody
17     public Integer[] test(@RequestParam("datas[]") Integer[] ids){
18         System.out.println("ids==" + ids);
19         return ids;
20     }
21 }

注意:

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

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

实现方式三

 前端页面

 1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
 2 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 3 <html>
 4 <head>
 5     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 6     <title>测试</title>
 7 </head>
 8 <body>
 9 <input type="button" name="request" value="请求后台"
10        style="width:200px;height:50px;background-color:red;margin-bottom:20px;">
11 <div name="rs"></div>
12 <input type="checkbox" name="se" value="1">hafiz.zhang<br/>
13 <input type="checkbox" name="se" value="2">jack.chen<br/>
14 <input type="checkbox" name="se" value="3">lili.wang<br/>
15 <script type="application/javascript" src="js/jquery-1.11.1.min.js"></script>
16 <script type="text/javascript">
17 
18     $("input[name='request']").click(function () {
19         var data = [];
20         $("input[name='se']").each(function () {
21             if ($(this).prop("checked")) {
22                 data.push($(this).val());
23             }
24         });
25         $.ajax({
26             type: "post",
27             url: "/test/index",
28             data: {"datas": data.join()}
29             dataType: "json",
30             success: function (data) {
31                 var str = "";
32                 for (var i = 0; i < data.length; i++) {
33                     str += ";name=" + data[i];
34                 }
35                 $("div[name='rs']").html(str);
36             },
37             error: function () {
38                 alert("出错啦");
39             }
40         });
41     });
42 </script>
43 </body>
44 </html>

后端代码

  1)通过数组接收

 1 package com.hafiz.www.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.RequestMethod;
 6 import org.springframework.web.bind.annotation.RequestParam;
 7 import org.springframework.web.bind.annotation.ResponseBody;
 8 
 9 import java.util.ArrayList;
10 import java.util.List;
11 
12 /**
13  * Desc:测试控制器
14  * Created by hafiz.zhang on 2017/7/2.
15  */
16 @Controller
17 @RequestMapping("/test")
18 public class TestController {
19     @RequestMapping(value = "/index", method = RequestMethod.POST)
20     @ResponseBody
21     public Integer[] test(@RequestParam("datas") Integer[] ids) {
22         System.out.println("ids=" + ids);
23         return ids;
24     }
25 }

  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)@ResponseBodypublic 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

转载于:https://www.cnblogs.com/hafiz/p/5498936.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/373034.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Maven集成测试和Spring Restful Services

介绍 我的原始博客通过一个非常简单的示例展示了如何分离Maven单元和集成测试。 http://johndobie.blogspot.com/2011/06/seperating-maven-unit-integration-tests.html此后&#xff0c;许多人要求我提供比最初使用的示例更实际的示例。 这篇文章展示了如何在实际环境中&#…

玩cf出现outofmemory_CF画质粗糙平衡感人,却能历经十年经久不衰,靠的是什么?...

Hello大家好&#xff0c;我是沐辰。《穿越火线》这款游戏国内运营时间已长达十年&#xff0c;从最早接触这款游戏开始&#xff0c;很多玩家都在这里烙刻下了许多关于青春的回忆。CF的许多问题一直颇受诟病&#xff0c;例如落后且粗糙的画质、英雄级武器与平民武器的巨大差距、千…

jquery遍历ajax返回的json数据

我们以前在前端遍历ajax拿到的数据一般都是用for或其他方式遍历&#xff0c;这样做麻烦且费事&#xff0c;效率不高&#xff0c;下面提供一个函数&#xff0c;只需调用函数即可把数据遍历出来&#xff0c;方便高效。 html代码&#xff1a; <html> <head><script…

Apache JMeter:随心所欲进行负载测试

这是有关使用Apache JMeter进行负载测试的第二篇文章&#xff0c;请在此处阅读第一篇文章&#xff1a; 有关对关系数据库进行负载测试的分步教程。 JMeter有很多采样器 。 如果您需要JMeter不提供的采样器&#xff0c;则可以编写自定义采样器。 &#xff08;自定义采样器在JMet…

html5历史管理

在网易云课堂上看了妙味课堂的关于html5历史管理的课程&#xff0c;在这里做一下笔记。 单页面或ajax局部刷新的页面中&#xff0c;没有办法通过前一步和后一步得到历史访问数据&#xff0c;此时有两种方法可以解决这个问题&#xff1a; 1.onhashchange事件&#xff0c;示例代码…

elementui下拉框 清空_巧妙解决element-ui下拉框选项过多的问题

1. 场景描述不知道你有没有这样的经历&#xff0c;下拉框的选项很多&#xff0c;上万个选项甚至更多&#xff0c;这个时候如果全部把数据放到下拉框中渲染出来&#xff0c;浏览器会卡死&#xff0c;体验会特别不好用人会说element-ui的select有一个remote-method&#xff0c;支…

致敬词

见义勇为致敬词 面对灾难和死神&#xff0c;你们大义凛然、知险而上&#xff0c;把平安和生机留给他人&#xff0c;把困难和危险留给自己。巍巍乎高山景行&#xff0c;铮铮然铁骨侠风&#xff1b;壮志谱传奇&#xff0c;热血写春秋。你们是&#xff1a;百姓英雄&#xff0c;平安…

MOXy作为您的JAX-RS JSON提供程序–客户端

最近&#xff0c;我发布了如何利用EclipseLink JAXB&#xff08;MOXy&#xff09;的JSON绑定来创建RESTful服务。 在本文中&#xff0c;我将演示在客户端利用MOXy的JSON绑定有多么容易。 MOXy作为您的JAX-RS JSON提供程序–服务器端 MOXy作为您的JAX-RS JSON提供程序–客户端 …

经常使用计算机的孩子,常玩电脑对孩子负面影响大,家长们不容小觑!

相信不少的家庭都会备有电脑&#xff0c;人们在网络世界里面能够找到自己需要的东西。不仅是大人喜欢玩电脑&#xff0c;小孩也喜欢玩电脑。然而常玩电脑对孩子负面影响大吗&#xff1f;有多大&#xff1f;一、行为问题全国青少年教育协会指出&#xff0c;5岁以下的使用电脑的孩…

基于SpringBoot的养老院管理系统

文章目录 项目介绍主要功能截图:部分代码展示设计总结项目获取方式🍅 作者主页:超级无敌暴龙战士塔塔开 🍅 简介:Java领域优质创作者🏆、 简历模板、学习资料、面试题库【关注我,都给你】 🍅文末获取源码联系🍅 项目介绍 基于SpringBoot的养老院管理系统,java项…

外呼机器人起名_智能外呼机器人,目前都有哪些公司做产品?

做智能外呼机器人的企业现在已经挺多了&#xff0c;比如各个答案中提到的各家的产品。它的市场认可度也比较高&#xff0c;大家都知道它能用于通知、回访、问卷调查、营销等业务场景。外呼机器人的价值很好衡量&#xff0c;用了外呼机器人后&#xff0c;能给企业赚多少钱&#…

VMware下ubuntu与Windows实现文件共享的方法

最近安装caffe需要将Windows下文件拷贝到ubuntu16.04下&#xff0c;就进行了共享文件夹的设置&#xff0c;期间遇到一些困难&#xff0c;记录下来&#xff0c;方便以后遇到此类问题不再困惑。 &#xff08;记录只为更好的分享&#xff09; 言归正传&#xff1a; 1、首先需要在u…

前端开发流程

一般都是在我们开发一个项目之前我们会进行一个讨论会&#xff0c;然后一起分析一下这个项目应该怎么去做&#xff0c;那些地方可以用最新的一些技术&#xff0c;那些技术有兼容问题&#xff0c;哪些可以实现&#xff0c;哪些不可以实现&#xff0c;这些讨论完以后&#xff0c;…

TestNG和Maven配置指南

为了有用&#xff0c;自动测试应该运行得非常快。 否则&#xff0c;将不会在开发期间经常运行&#xff0c;甚至在开发人员工作站的默认配置中将被忽略。 最简单的规则是仅编写小型单元测试&#xff0c;该测试将模拟给定类的邻居。 但是&#xff0c;有时在IoC容器上下文&#xf…

微型计算机广告牌实验报告,微型计算机实验报告1资料.doc

实验报告1. 实验名称程序编译及调试2. 实验目的掌握汇编语言语句格式&#xff0c;程序结构&#xff0c;上机调试步骤和各种类型程序的设计方法。了解汇编语言的基本语法&#xff0c;汇编程序的功能和汇编&#xff0c;调试过程&#xff0c;伪指令&#xff0c;汇编语言程序设计&a…

mybatis入门-新手注意问题

参数问题 在映射文件中通过parameterType指定输入参数的类型&#xff1b;在映射文件中通过resultType指定输出结果的类型。 占位符和拼接符问题 #{}表示一个占位符号&#xff0c;#{}接收输入参数&#xff0c;类型可以是简单类型&#xff0c;pojo、hashmap。 如果接收简单类型&a…

python文件管理包_Python标准库04 文件管理 (部分os包,shutil包)

Python标准库04 文件管理 (部分os包&#xff0c;shutil包)在操作系统下&#xff0c;用户可以通过操作系统的命令来管理文件&#xff0c;参考。Python 标准库则允许我们从 Python 内部管理文件。相同的目的&#xff0c;我们有了两条途径。尽管在 Python 调用标准库的方式不如操作…

Delphi Berlin 10.1 for iOS 成生 info.plist 顺序改变了

在 Delphi Seattle 10 update 1 版本&#xff08;含之前版本&#xff09;&#xff0c;只要 Project > Build 会立即生成 info.plist 如果需要修改 info.plist 可以利用 TMS 提供的修改工具 Fixing on iOS 9 来修改。 在 Delphi Berlin 10.1 版本&#xff0c;顺序改变了&…

MANIFEST.MF和feature.xml版本控制规则

我永远忘记了OSIF插件和功能的 MANIFEST.MF和feature.xml中的依赖项声明的规则是什么。 谷歌搜索经常导致沮丧而不是答案。 所以&#xff0c;因为今天我实际上找到了这些规则的简要列表&#xff0c;所以我想在这里重新发布它们&#xff0c;并进行一些小的修改以帮助阐明。 OSGi…

远程桌面连接时无法访问远程计算机的计算机属性提示系统调用失败,远程过程调用失败【应对技巧】...

喜欢使用电脑的小伙伴们一般都会遇到win7系统远程过程调用失败的问题&#xff0c;突然遇到win7系统远程过程调用失败的问题就不知道该怎么办了&#xff0c;其实win7系统远程过程调用失败的解决方法非常简单&#xff0c;按照1&#xff1a;第一步我们可以看到sql server数据库出现…