首页 > 解决方案 > 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 变量(不可更改,由我的客户请求)。

我真的迷失在这个问题上。我很想有一些方向。

标签: javascriptjavaajaxjspservlets

解决方案


推荐阅读