【问题标题】:Get HTTP status code in asynchronous way以异步方式获取 HTTP 状态码
【发布时间】:2016-11-08 14:11:32
【问题描述】:

我想在 Java 中的 doPost 方法结束之前获取 HTTP 状态代码。例如在Python中有self.send_response(200),它以异步方式发送状态?

 /**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 * response)
 *
 */
@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    //Final result object


    //I want to send a http status code 200 before the task running

    myThreadPool = Executors.newFixedThreadPool(2);
    Future taskOne = myThreadPool.submit(new Runnable() {
        @Override
        public void run() {
            try {
                try {
                    // My first task
                } catch (ServletException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    });

    // Task two 
    .
    .

【问题讨论】:

  • 您能否向我们展示您目前的代码并告诉我们您正在使用哪些框架?
  • 你的问题真的不清楚。您想异步检索一个 int 吗? docs.oracle.com/javaee/7/api/javax/servlet/http/…
  • 嗨 @Taylor,我希望我的 API 以异步方式工作,所以,首先,我将发送我的请求,服务器应该以 http 代码 200 响应并在后台继续执行我的 doPost ,所有任务完成后它会发送响应。
  • walkeros 下面的回答是一个不错的选择。另外,看看 Java 或 NodeJS(不是 java)中的反应式编程。

标签: java http servlets


【解决方案1】:

我不完全确定您发布的代码的意图是什么,但我可以猜想您想要某种异步处理,以便您可以在请求完成之前向客户端发送一些数据?

请参考异步 servlet,例如此处所述:https://blogs.oracle.com/enterprisetechtips/entry/asynchronous_support_in_servlet_3

甚至还有一个很好的例子,它似乎在服务于我认为你想要实现的目标:

@WebServlet("/foo" asyncSupported=true)
   public class MyServlet extends HttpServlet {
        public void doGet(HttpServletRequest req, HttpServletResponse res) {
            ...
            AsyncContext aCtx = request.startAsync(req, res);
            ScheduledThreadPoolExecutor executor = new ThreadPoolExecutor(10);
            executor.execute(new AsyncWebService(aCtx));
        }
   }

   public class AsyncWebService implements Runnable {
        AsyncContext ctx;
        public AsyncWebService(AsyncContext ctx) {
            this.ctx = ctx;
        }
        public void run() {
            // Invoke web service and save result in request attribute
            // Dispatch the request to render the result to a JSP.
            ctx.dispatch("/render.jsp");
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2018-10-28
    • 2019-03-20
    • 2015-10-31
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多