【servlet3.0新特性】异步监听器实例

异步监听器用来监听异步处理事件;即“三”中讲到的知识点;

此监听器用户servlet3.0异步处理中,此监听器类似于ServletContextListener的机制;

只需要实现AsyncListener接口即可;

此接口有4个方法:
public void onStartAsync(AsyncEvent event)throws IOException;

public void onComplete(AsyncEvent event);

public void onTimeout(AsyncEvent event);

public void onError(AsyncEvent event);

以下是监听器实现的代码:

import java.io.IOException;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;

/**
 *
 */
public class MyListener implements AsyncListener {

	@Override
	public void onComplete(AsyncEvent event) throws IOException {
		System.out.println("-----异步监听完成");
	}

	@Override
	public void onError(AsyncEvent arg0) throws IOException {
	}

	@Override
	public void onStartAsync(AsyncEvent arg0) throws IOException {		
	}

	@Override
	public void onTimeout(AsyncEvent arg0) throws IOException {
	}

}

在Servlet异步处理处添加:

actx.addListener(new MyListener());就可以添加监听器,每当异步处理完成时就会触发onComplete()事件

AsyncContext actx = request.startAsync();
        actx.addListener(new MyListener());
        actx.setTimeout(30 * 3000);
        actx.start(new MyThread(actx));   

启动tomcat 输入URL执行完程序控制台输出"-----异步监听完成"

来源://作者:/更新时间:2013-11-15
相关文章
评论:
验证码:
匿名评论: