gpt4 book ai didi

java - 如何从同一个 servlet 递归调用 servlet

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:39:40 26 4
gpt4 key购买 nike

我想从自身递归调用一个 servlet,直到我的操作完成。我需要这样做的原因是因为我的托管服务有一个硬期限,所有 RPC 调用都必须满足该期限。因此,我需要将操作分解为可管理的 block ,并为每个 block 递归调用 servlet,直到操作完成。

我觉得下面的代码应该可以工作,但是当 HttpURLConnection 打开并连接时它不会调用 servlet。也没有错误被抛出。任何帮助将不胜感激。

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class ServletExample extends HttpServlet {

HttpServletRequest request;

public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

request = req;

String strRequestIndex = request.getParameter("requestIndex");
int intRequestIndex = 0;

if (strRequestIndex != null) {
intRequestIndex = Integer.parseInt(strRequestIndex);
}

if (intRequestIndex < 10) {
try {
callSameServlet(intRequestIndex);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

private void callSameServlet(int requestIndex) throws Exception {

URL recursiveUrl = new URL(request.getRequestURL().toString()
+ "?requestIndex=" + (requestIndex + 1));

HttpURLConnection connection = (HttpURLConnection) recursiveUrl
.openConnection();

connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.connect();

DataOutputStream dos = new DataOutputStream(
connection.getOutputStream());

dos.flush();
dos.close();

}

}

最佳答案

至于您的问题中暴露的技术问题:URLConnection 被延迟执行。 URLConnection#getOutputStream()在您的代码中只返回一个句柄来编写 request 正文。您需要使用 URLConnection#getInputStream() 实际上触发 HTTP 请求并获取响应正文。

另见:


但是您的代码中还有更多问题:

您正在触发一个 POST 请求,但是您的 servlet 中没有任何地方定义 doPost() 方法。您需要触发一个普通的 GET 或实现 doPost()。但是,通过调查上面链接中描述的获得的错误响应,这将是显而易见的。

此外,您的 servlet 不是线程安全的。您不应该将请求/ session 范围的数据声明/分配为 servlet 的实例变量。阅读this answer了解更多。

最后,您是否考虑过使用 RequestDispatcher#include()反而?这将在内部处理并为您节省触发 HTTP 请求的成本/开销。

request.getRequestDispatcher("servleturl").include(request, response);

然后您可以使用请求属性而不是请求参数。顺便说一下,整个功能需求毫无意义。我只是对要递归执行的代码使用 forwhile 循环。但这是一个不同的问题。

关于java - 如何从同一个 servlet 递归调用 servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4246862/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com