- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我想从自身递归调用一个 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);
然后您可以使用请求属性而不是请求参数。顺便说一下,整个功能需求毫无意义。我只是对要递归执行的代码使用 for
或 while
循环。但这是一个不同的问题。
关于java - 如何从同一个 servlet 递归调用 servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4246862/
我是一名优秀的程序员,十分优秀!