Servlet - Servlet3.0の非同期処理のサポート
Servlet3.0ではAsyncContextクラスを使って非同期処理を行う。
ServletはServletRequestの下記メソッドを使って非同期開始、AsyncContext生成を行う。
1. AsyncContext startAsync()
2. AsyncContext startAsync(ServletRequest request, ServletResponse response)
AsyncServlet.java |
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns="/async", asyncSupported=true)
public class AsyncServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// set responce contecTtype
response.setContentType("text/html;charset=UTF-8");
// 非同期開始
AsyncContext act = request.startAsync();
act.start(new RunnableClass(act));
// output stream
PrintWriter out = response.getWriter();
out.println("<title>");
out.println("it is AsyncServlet.");
out.println("</title>");
out.println("非同期テストサブレットです。");
out.println("続く内容は5秒後に表示されます。"); out.println("<br/>");
out.flush();
}
// 非同期処理内部クラス
private class RunnableClass implements Runnable{
private AsyncContext act = null;
public RunnableClass(AsyncContext act) {
this.act = act;
}
@Override
public void run() {
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
ServletRequest request = act.getRequest();
request.setAttribute("name", "alex");
// async.jsp指定
act.dispatch("/async.jsp");
}
}
}
|