unknown
unknown

Reputation: 343

JAVA API Servlet Asynchronous Call

I wanted to conduct an asynchronous call in Java API Servlet. I used this at the top of my class

  @WebServlet(name="asyncServlet2",value = {"/async"},asyncSupported = true,urlPatterns="/async")

My intention is since the API call will be a longer process that it can display whether the process kicked off or not instantly, rather than when completed.

I couldn't figure out which functionality of the Java Servlet 3.0 will let me display the message instantly. Thanks for your help!

Upvotes: 0

Views: 147

Answers (1)

PeakCode
PeakCode

Reputation: 150

It depends on what the response is expected to look like. If you are in full control over how the response should look, this should be feasible. For example:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    resp.setContentType("text/plain");
    AsyncContext context = req.startAsync();

    // Possibly in another thread:

    // Initiate call to external service.

    resp.getWriter().write("Call initiated OK.\n\n");
    resp.getWriter().flush();

    // Definitely in another thread:

    // Call to external service returns.

    resp.getWriter().write("Result: " + result);
    resp.getWriter().flush();
    context.complete();
}

Note that the response will come back as 200 OK even though the call to external service might fail in the end.

Upvotes: 1

Related Questions