javascript - Java Servlet 返回错误数据?
问题描述
我正在研究 [JSP <-> Javascript <-> Servlet <-> Restful Api] 项目。我创建了一个名为“CRUD”的 servlet,它使用 ID 和 URL 接收来自整个 Web 的所有请求,然后使用 API 返回的数据返回一个通用答案。
当我想同时发出多个请求时,我的问题开始了,servlet 将错误的数据返回给 ajax 请求。例如,如果我提出 3 个请求,客户、产品和价格,客户收到产品,产品收到价格,价格收到客户。
这只发生在我同时执行多个请求时,如果我一个接一个地执行,它会正确接收到数据。
例子:
Javascript:
$(document).ready(function() {
$.ajax({url: 'crud', type: 'GET', dataType: 'JSON', data: {
requestID: 'customers'
}).done(function(data) {
//this recieves products
});
$.ajax({url: 'crud', type: 'GET', dataType: 'JSON', data: {
requestID: 'products'
}).done(function(data) {
//this recieves prices
});
$.ajax({url: 'crud', type: 'GET', dataType: 'JSON', data: {
requestID: 'prices'
}).done(function(data) {
//this recieves customers
});
});
CRUD Servlet:
HashMap<String, String> urls;
static {
urls = new HashMap();
urls.put("customers", "api/customer");
urls.put("products", "api/products");
urls.put("prices", "api/prices");
}
@WebServlet(name = "CRUD", urlPatterns = {"/CRUD"})
public class CRUD extends HttpServlet {
JSONObject wsResponse = new JSONObject();
/*
Format:
wsResponse: {
type: 'success' -> this can be success/error
data: {} -> this is the json object returned by the api/webservice
}
*/
String requestURL = (HashMap<String, String>) urls.get(request.getParameter("requestID"));// -> HashMap with the paths from the api based on an ID
String authToken = request.getSession().getAttribute("token");
wsResponse = getData(authToken,requestURL);
response.getWritter().print(wsResponse);
}
public JSONObject getData(String authToken, String requestURL) {
JSONObject wsResponse = new JSONObject();
try {
URL url = new URL(requestURL);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestProperty("Authorization", "Bearer " + authToken);
http.setRequestMethod("GET");
Integer response_code = http.getResponseCode();
if (response_code == 200) {
wsResponse.put("type", "success");
wsResponse.put("data", new String(IOUtils.toByteArray(http.getInputStream()), "UTF-8"));
} else {
wsResponse.put("type", "error");
wsResponse.put("data", "Error while recieving data");
}
}catch(Exception e) {
wsResponse.put("type", "error");
wsResponse.put("data", "Error while working on the request")
}
return wsResponse;
}
我究竟做错了什么?我能做些什么来解决这个问题?这是管理多个请求的“好”方式吗?
我不直接对 API 执行操作的原因是隐藏 URL 和 AuthToken 变量(不可更改,由我的客户请求)。
我真的迷失在这个问题上。我很想有一些方向。
解决方案
推荐阅读
- spring - 现实世界中的隔离级别用例
- r - 图例匹配 ggplot2 中的线型
- promise - 在 useEffect() 中修改对象不会更新状态
- html - HTTP 加载失败,状态为 403。加载媒体资源
- javascript - 使绝对链接的容器可变并且不拉伸视口的整个高度?
- vue.js - Vue.js:如何转换给定对象中的特定数据?
- excel - 我在使用 Excel VBA 创建 Pivot 时出错
- android - 计算数字的百分比
- python - 一个函数,它接受一个列表值并返回一个字符串,其中所有项目由逗号和空格分隔,并在最后一项之前插入
- msbuild - -t:go 标志在 MSBuild 中的作用是什么?