歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

Tomcat7實現Servlet3異步請求

pom.xml:
 
1
<dependency>
2
    <groupId>javax.servlet</groupId>
3
    <artifactId>javax.servlet-api</artifactId>
4
    <version>3.0.1</version>
5
    <scope>provided</scope>
6
</dependency>
web.xml:
 
1
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
2
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
4
    <display-name>Servlet3-Demo</display-name>
5
</web-app>
AsyncServlet:
 
01
@WebServlet(value = "/async-demo", asyncSupported = true)
02
public class AsyncServlet extends HttpServlet {
03
 
04
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
05
 
06
    public void doGet(HttpServletRequest req, HttpServletResponse res) {
07
        AsyncContext aCtx = req.startAsync(req, res);
08
 
09
        executor.execute(new AsyncHandler(aCtx));
10
    }
11
 
12
}
AsyncHandler:
 
01
public class AsyncHandler implements Runnable {
02
 
03
    private AsyncContext ctx;
04
 
05
    public AsyncHandler(AsyncContext ctx) {
06
        this.ctx = ctx;
07
    }
08
 
09
    @Override
10
    public void run() {
11
        System.out.println("Dispatch Time: " + System.currentTimeMillis());
12
 
13
        ctx.dispatch("/index.jsp");
14
    }
15
 
16
}


摘自 Neron.L的博客
Copyright © Linux教程網 All Rights Reserved