使用axios发送多个参数的post请求(Servlet)
字符串,并通过字节流传递(服务器通过字节流接收),并且。来获取参数,并且请求的方式仍然是。来获取请求参数,是获取不到的。请求的数据被封装在了。
·
正确示例
使用字符输入流的方式来读取请求参数
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script> window.onload = function () { axios({ method: "post", url: "http://localhost:8080/ajax-test/test", data: { people: { name: '张三', age: 18 } } }).then(function (resp) { console.log(resp) }) } </script> </body> </html>
servlet
@WebServlet("/test") public class AxiosTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf8"); System.out.println(req.getReader().readLine()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
- 控制台输出
{"people":{"name":"张三","age":18}}
错误示例
-
如果
servlet
中是通过getParameter()
来获取请求参数,是获取不到的@WebServlet("/test") public class AxiosTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf8"); Object people = req.getParameter("people"); System.out.println(people); // 输出结果是 null } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
-
原因:
getParameter()
获取的是请求头中的参数,而post
请求的数据被封装在了请求体中
使用axios
时,会将数据变成json
字符串,并通过字节流传递(服务器通过字节流接收),并且只有一行 -
如果希望使用
getParameter()
来获取参数,并且请求的方式仍然是post
,可以将参数放到url
中
例如:axios
:axios({ method: "post", url: "http://localhost:8080/ajax-test/test?msg=hello", data: { people: { name: '张三', age: 18 } } }).then(function (resp) { console.log(resp) })
servlet
@WebServlet("/test") public class AxiosTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf8"); System.out.println(req.getParameter("msg")); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
- 控制台输出
hello
更多推荐
已为社区贡献1条内容
所有评论(0)