在Java中接收前端传递的数组有两种方法:使用请求参数:适用于少量数据,通过请求URL传递,用HttpServletRequest获取。使用请求正文:适用于大量数据,通过JSON或XML格式传递,用@RequestBody注解映射到Java对象。

如何使用Java接收前端传递的数组
在Java中,接收前端传递的数组可以通过使用请求参数或请求正文两种方式。
1. 使用请求参数
这种方法适用于需要传递少量数据的情况。可以在请求URL中添加参数,并在Java中使用HttpServletRequest对象获取这些参数。
立即学习“Java免费学习笔记(深入)”;
示例:
前端代码:
阿里云-虚拟数字人
阿里云-虚拟数字人是什么? …
2 查看详情
const array = [1, 2, 3];const url = 'http://localhost:8080/api/v1/endpoint';const params = new URLSearchParams({ 'array': array});fetch(url + '?' + params);
Java代码:
import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/api/v1/endpoint")public class EndpointServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String[] array = req.getParameterValues("array"); // 处理数组... }}
2. 使用请求正文
这种方法适用于需要传递大量数据的情况。可以在请求正文中使用JSON或XML等格式传递数据,并在Java中使用@RequestBody注解将正文映射到一个Java对象。
示例:
前端代码:
const array = [1, 2, 3];const url = 'http://localhost:8080/api/v1/endpoint';fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ 'array': array })});
Java代码:
import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/api/v1/endpoint")public class EndpointServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String contentType = req.getContentType(); if (contentType.equals("application/json")) { BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream())); String json = reader.readLine(); JSONObject jsonObject = new JSONObject(json); int[] array = jsonObject.getJSONArray("array").toIntArray(); // 处理数组... } }}
以上就是java怎么接受前端传的数组的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/410430.html
微信扫一扫
支付宝扫一扫