You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Servlet中获取xhrArgs发送的PostData?Dojo调用问题及替代方案

我之前也碰到过类似的问题,大概率是Dojo请求的配置没做对,或者Servlet端的解析方式不对。先给你梳理下Dojo正确调用Servlet POST的写法,再给几个替代方案,你可以逐一排查试试:

一、先排查Dojo请求的配置问题

首先,Dojo的xhr请求如果没设置正确的请求头或者数据格式,Servlet确实拿不到POST数据。这里给你两种常见场景的示例:

1. 发送表单格式数据(Servlet用getParameter接收)

前端代码:

require(["dojo/request/xhr"], function(xhr) {
  xhr("/your-servlet-path", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded" // 这个是关键,必须设置
    },
    data: "username=test&age=25" // 手动拼接成表单格式,或者用dojo/io-query转换对象
  }).then(function(response) {
    console.log("请求成功:", response);
  }, function(error) {
    console.error("请求失败:", error);
  });
});

如果要发送JS对象,可以用dojo/io-query的objectToQuery方法简化转换:

require(["dojo/request/xhr", "dojo/io-query"], function(xhr, ioQuery) {
  const postData = { username: "test", age: 25 };
  xhr("/your-servlet-path", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    data: ioQuery.objectToQuery(postData)
  }).then(...);
});

对应的Servlet代码:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String username = request.getParameter("username");
  String age = request.getParameter("age");
  // 处理你的业务逻辑
  response.getWriter().write("数据接收成功");
}

2. 发送JSON格式数据(Servlet需要读取输入流解析)

如果要发送JSON格式,请求头和数据序列化必须对应:
前端代码:

require(["dojo/request/xhr"], function(xhr) {
  const postData = { username: "test", age: 25 };
  xhr("/your-servlet-path", {
    method: "POST",
    headers: {
      "Content-Type": "application/json" // JSON格式的请求头
    },
    data: JSON.stringify(postData) // 必须转成JSON字符串
  }).then(function(response) {
    console.log("请求成功:", response);
  }, function(error) {
    console.error("请求失败:", error);
  });
});

对应的Servlet代码(需要手动读取请求体解析JSON,这里用Gson库做示例):

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // 读取请求体内容
  BufferedReader reader = request.getReader();
  StringBuilder sb = new StringBuilder();
  String line;
  while ((line = reader.readLine()) != null) {
    sb.append(line);
  }
  String jsonStr = sb.toString();
  
  // 解析JSON为实体类
  Gson gson = new Gson();
  User user = gson.fromJson(jsonStr, User.class);
  
  // 处理业务逻辑
  response.setContentType("application/json");
  response.getWriter().write(gson.toJson("JSON数据接收成功"));
}

// 对应的User实体类
class User {
  private String username;
  private int age;
  // 别忘了添加getter和setter方法
}
二、如果Dojo还是有问题,试试这些替代方案

1. 原生XMLHttpRequest(兼容性拉满)

最基础的方案,完全不需要依赖第三方库:

const xhr = new XMLHttpRequest();
xhr.open("POST", "/your-servlet-path", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function() {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log("请求成功:", xhr.responseText);
  } else {
    console.error("请求失败:", xhr.statusText);
  }
};
xhr.onerror = function() {
  console.error("网络请求出错");
};
xhr.send("username=test&age=25"); // 发送JSON的话改成JSON.stringify(postData),并修改请求头为application/json

2. Fetch API(现代浏览器首选)

写法更简洁,Promise风格更易维护:

// 发送表单格式
fetch("/your-servlet-path", {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  body: "username=test&age=25"
})
.then(response => response.text())
.then(data => console.log("请求成功:", data))
.catch(error => console.error("请求失败:", error));

// 发送JSON格式
fetch("/your-servlet-path", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({ username: "test", age: 25 })
})
.then(response => response.json())
.then(data => console.log("请求成功:", data))
.catch(error => console.error("请求失败:", error));

3. Axios(第三方库,省心首选)

如果项目允许引入第三方库,Axios会帮你处理大部分细节:

// 发送表单格式
axios.post("/your-servlet-path", { username: "test", age: 25 }, {
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  transformRequest: [(data) => {
    // 自动把对象转成表单格式
    return Object.keys(data).map(key => `${key}=${encodeURIComponent(data[key])}`).join('&');
  }]
})
.then(response => console.log("请求成功:", response.data))
.catch(error => console.error("请求失败:", error));

// 发送JSON格式(Axios默认就是JSON格式,无需额外配置)
axios.post("/your-servlet-path", { username: "test", age: 25 })
.then(response => console.log("请求成功:", response.data))
.catch(error => console.error("请求失败:", error));
几个关键排查点
  • 先打开浏览器开发者工具的Network面板,确认POST请求的Request Payload或Form Data里确实有数据,同时检查请求头的Content-Type是否和发送的数据格式匹配;
  • 确认Servlet的路径是否正确,有没有出现404错误;
  • 如果是JSON格式,Servlet端不能用getParameter方法,必须读取请求体解析;
  • 检查Servlet的doPost方法是否被正确重写,有没有拼写错误。

内容的提问来源于stack exchange,提问作者sujeeth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:14:18