Fork me on GitHub
Edit on GitHub << back to Plugins

Async Plugin

Description

The Async plugin allows to implement actions as using an Asynchronous Processing available as from Servlet API 3. It’s a thin layer over the Servlet async layer.

Simple usage

The example code below shows how to implement and use async actions. Please check an async action example in our Showcase app.

Action

public class AsyncAction {

    public Callable<String> execute() throws InterruptedException {
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
                waitForEvent();
                return "success";
            }
        };
    }

    private void waitForEvent() throws InterruptedException {
        Thread.sleep(40000);
    }
}

struts.xml

<action name="async" class="com.company.struts.AsyncAction">
    <result name="success" type="json"/>
</action>

web.xml

You must define the Struts Servlet to allow support Async actions.

<servlet>
    <servlet-name>strutsServlet</servlet-name>
    <servlet-class>org.apache.struts2.dispatcher.servlet.StrutsServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
</servlet>

<servlet-mapping>
<servlet-name>strutsServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

Customize timeout

Action

public class AsyncAction {

    public Callable<String> execute() throws InterruptedException {
        return new AsyncAction(60000/*timeout*/, new Callable<String>() {
            @Override
            public String call() throws Exception {
                waitForEvent();
                return "success";
            }
        });
    }

    private void waitForEvent() throws InterruptedException {
        Thread.sleep(40000);
    }
}

Serializing multiple async tasks

Action

public class AsyncAction {

    public Callable<String> execute() throws InterruptedException {
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
                waitForEvent1();
                return new Callable<String>() {

                    @Override
                    public String call() throws Exception {
                        waitForEvent2();
                        return "success";
                    }
                };
            }
        };
    }

    private void waitForEvent1() throws InterruptedException {
        Thread.sleep(40000);
    }

    private void waitForEvent2() throws InterruptedException {
        Thread.sleep(40000);
    }
}