Pregunta

I am figuring out how a asynchronous servlet flow behaves asynchronously.

If there is a servlet Servlet_1,and we are calling a utility class SampleUtility's util method from the servlet and returning some value to the servlet after some sort of manipulation in the util method.

So, for the flow to asynchronous do we need to pass asyncContext to the util method,or simply starting the asynccontext by the statement

 AsyncContext asyncContext = request.startAsync();

will be enough for the flow to be asynchronous??

¿Fue útil?

Solución

For a Servlet to be Asynchronous 3 steps need to be performed necessarily.

  1. Annote the web servlet annotation as

    @WebServlet(urlPatterns={“/servletexample”},aysncSupported=true)

    Marking it asyncSupported true will make capable of Asynchronous flow.

  2. Start the AsyncContext by the following statement

    AsyncContext ac=request.startAsync();

  3. Lastly implement the startAsync()

    asyncContext.start(new Runnable(){ public void run(){ //Write the non-blocking code here } }

Otros consejos

will be enough for the flow to be asynchronous??

No, this will not be enough. To enable asynchronous processing on a servlet, set the parameter asyncSupported to true on the @WebServlet annotation as follows:

  @WebServlet(urlPatterns={"/asyncservlet"}, asyncSupported=true)
  public class AsyncServlet extends HttpServlet { ... }

For details, go through this tutorial.

AsyncContext.forward(path) and AsyncContext.forward() that forwards the request back to the container so you can use frameworks like JSP to generate the response. So you need to pass asyncContext to the method because AsyncContext provides methods to get the ServletRequest and ServletResponse object references.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top