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

如何使用Java接收前端传递的数组
在Java中,接收前端传递的数组可以通过使用请求参数或请求正文两种方式。
1. 使用请求参数
这种方法适用于需要传递少量数据的情况。可以在请求URL中添加参数,并在Java中使用HttpServletRequest对象获取这些参数。
立即学习“Java免费学习笔记(深入)”;
示例:
前端代码:
<code class="javascript">const array = [1, 2, 3];
const url = 'http://localhost:8080/api/v1/endpoint';
const params = new URLSearchParams({
'array': array
});
fetch(url + '?' + params);</code>Java代码:
<code class="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");
// 处理数组...
}
}</code>2. 使用请求正文
这种方法适用于需要传递大量数据的情况。可以在请求正文中使用JSON或XML等格式传递数据,并在Java中使用@RequestBody注解将正文映射到一个Java对象。
示例:
前端代码:
<code class="javascript">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
})
});</code>Java代码:
<code class="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();
// 处理数组...
}
}
}</code>以上就是java怎么接受前端传的数组的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号