- 浏览: 937353 次
- 性别:
- 来自: 成都
文章分类
最新评论
Servlet3.0提供异步处理
在以前的Servlet规范化,如果Servlet作为控制器调用了一个耗时的业务方法,那么必须等到业务方法完全返回之后才能生成响应,这将使用Servlet对业务方法的调用变成一种阻塞式的调用,因此效率比较低。
Servlet3.0规范引入了异步处理来解决这个问题,异步处理允许Servlet重新发起一条新线程去调用 耗时业务方法,这样就可以避免等待。
Servlet3.0的异步处理是通过AsyncContext类来处理的,Servlet可通过ServletRequest的如下两个方法开启异步调用,创建AsyncContext对象:
AsyncContext startAsync()
AsyncContext startAsync(ServletRequest,ServletResponse)
异步处理类AsyncServlet.java
package aniyo.servlet.async; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.AsyncContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet 3.0提供的异步处理 * 异步操作通过AsyncContext类来处理,通过startAsync()方法来开启异步调用 * @author aniyo * blog:http://aniyo.iteye.com * */ @WebServlet(name="asyncServle",urlPatterns="/asyncServlet",asyncSupported=true) public class AsyncServlet extends HttpServlet { /* (non-Javadoc) * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=GBK"); PrintWriter out = response.getWriter(); out.println("<title>异步调用示例</title>"); out.println("进入Servlet的时间:"+new Date()+".<br/>"); out.flush(); //创建AsyncContext,开始异步调用 AsyncContext actx = request.startAsync(); //设置异步调用的超时时长 actx.setTimeout(30*1000); //启动异步调用的线程 actx.start(new Executor(actx)); out.println("结束Servlet的时间:"+new Date()+".<br/>"); out.flush(); } }
线程类Executor.java
package aniyo.servlet.async; import java.util.ArrayList; import java.util.List; import javax.servlet.AsyncContext; import javax.servlet.ServletRequest; public class Executor implements Runnable{ private AsyncContext actx = null; public Executor(AsyncContext actx) { this.actx = actx; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { //等待5秒 try { Thread.sleep(5*1000); ServletRequest request = actx.getRequest(); List<String> books = new ArrayList<String>(); books.add("java"); books.add("oracle"); books.add("j2ee"); request.setAttribute("books", books); actx.dispatch("/async.jsp"); } catch (InterruptedException e) { e.printStackTrace(); } } }
跳转页面async.jsp
<%@page import="java.util.Date"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false"%> <%@ taglib prefix = "c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <ul> <c:forEach items="${books}" var="book"> <li> ${book } </li> </c:forEach> </ul> <%out.println("业务调用结束的时间:"+ new Date()); //完成异步调用 //request.getAsyncContext().complete(); %> </body> </html>
在jsp界面使用jstl表达式的时候需要使用jstl两个jar包,jstl.jar及standard.jar
- jstl1.2jar包.7z (778.1 KB)
- 下载次数: 97
评论
2 楼
string2020
2014-05-03
貌似原因是:
有了out.println 之后,就不能dispatch了
有了out.println 之后,就不能dispatch了
1 楼
string2020
2014-05-03
完全照着你的写,却是报错了
五月 03, 2014 10:03:42 下午 org.apache.catalina.core.ApplicationDispatcher invoke 严重: Servlet.service() for servlet jsp threw exception java.lang.IllegalStateException: Cannot create a session after the response has been committed at org.apache.catalina.connector.Request.doGetSession(Request.java:2924) at org.apache.catalina.connector.Request.getSession(Request.java:2300) at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:897) at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:229) at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:569) at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:514) at org.apache.jasper.runtime.PageContextImpl._initialize(PageContextImpl.java:147) at org.apache.jasper.runtime.PageContextImpl.initialize(PageContextImpl.java:126) at org.apache.jasper.runtime.JspFactoryImpl.internalGetPageContext(JspFactoryImpl.java:112) at org.apache.jasper.runtime.JspFactoryImpl.getPageContext(JspFactoryImpl.java:65) at org.apache.jsp.list_jsp._jspService(list_jsp.java:53) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748) at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:659) at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:625) at org.apache.catalina.core.AsyncContextImpl$1.run(AsyncContextImpl.java:237) at org.apache.catalina.core.AsyncContextImpl.doInternalDispatch(AsyncContextImpl.java:380) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:215) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.asyncDispatch(CoyoteAdapter.java:299) at org.apache.coyote.http11.AbstractHttp11Processor.asyncDispatch(AbstractHttp11Processor.java:1632) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:599) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) 五月 03, 2014 10:03:42 下午 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet [cn.cloud.action.LoginServlet] in context with path [/jdshop] threw exception [javax.servlet.ServletException: java.lang.IllegalStateException: Cannot create a session after the response has been committed] with root cause java.lang.IllegalStateException: Cannot create a session after the response has been committed at org.apache.catalina.connector.Request.doGetSession(Request.java:2924) at org.apache.catalina.connector.Request.getSession(Request.java:2300) at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:897) at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:229) at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:569) at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:514) at org.apache.jasper.runtime.PageContextImpl._initialize(PageContextImpl.java:147) at org.apache.jasper.runtime.PageContextImpl.initialize(PageContextImpl.java:126) at org.apache.jasper.runtime.JspFactoryImpl.internalGetPageContext(JspFactoryImpl.java:112) at org.apache.jasper.runtime.JspFactoryImpl.getPageContext(JspFactoryImpl.java:65) at org.apache.jsp.list_jsp._jspService(list_jsp.java:53) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748) at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:659) at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:625) at org.apache.catalina.core.AsyncContextImpl$1.run(AsyncContextImpl.java:237) at org.apache.catalina.core.AsyncContextImpl.doInternalDispatch(AsyncContextImpl.java:380) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:215) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.asyncDispatch(CoyoteAdapter.java:299) at org.apache.coyote.http11.AbstractHttp11Processor.asyncDispatch(AbstractHttp11Processor.java:1632) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:599) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745)
发表评论
-
object references an unsaved transient instance
2017-08-08 14:38 1795org.hibernate.TransientObject ... -
Jave获取当前日期的上一个月最后一天或者下一个月最后一天
2017-02-08 09:58 1322public final static Date addMo ... -
valid date
2017-02-04 16:37 955public final static boolea ... -
Row was updated or deleted by another transaction (or unsaved-value mapping was
2017-02-04 11:41 2606org.hibernate.StaleObjectState ... -
hibernate hql return object or list 指定类型
2017-01-25 17:58 902java.lang.ClassCastException: ... -
解决Maven/Ant中OutOfMemory错误
2017-01-12 11:06 866当Maven项目很大,或者你运行诸如 mvn site 这样 ... -
Row was updated or deleted by another transaction (or unsaved-value mapping was
2016-03-31 16:15 1119Row was updated or deleted by ... -
identifier of an instance of ……was alter from 2 to null
2016-03-29 09:32 1652Undefined Error: org.hibernate ... -
Caused by: org.hibernate.AssertionFailure: collection owner not associated with
2016-01-13 16:49 1499Caused by: org.hibernate.Asser ... -
遍历Set集合remove掉不需要的数据,List不能在遍历的时候remove
2015-12-29 15:33 2519for(Iterator<IAddress> ... -
oracle查询约束
2015-12-28 14:45 1387查询约束类型 select distinct constr ... -
should be mapped with insert="false" update="false"
2015-04-22 16:23 1381Caused by: org.hibernate.Mappi ... -
org.hibernate.PropertyAccessException: IllegalArgumentException occurred
2015-04-16 17:42 959org.hibernate.PropertyAccessEx ... -
no persistent classes found for query class
2015-04-13 16:54 1696no persistent classes found fo ... -
hql unexpected token: exchange
2015-03-13 10:12 1336ORB.thread.pool : 0line 1:1 ... -
从一个英文字符串中找出每个单词出现的频率
2015-03-06 14:56 1491import java.util.*; publi ... -
Caused by: java.io.IOException: Mismatched serialization UIDs
2015-02-04 10:51 1421Caused by: java.io.IOException ... -
Hibernate :Found shared references to a collection
2014-12-16 11:13 1105项目中在session.flush(); 抛了异常 遇到这 ... -
HibernateException: Illegal attempt to associate a collection with two open sess
2014-12-09 13:56 746项目中遇到这个 HibernateException: Il ... -
获取Float整型数据如何去掉小数点后面的小数点及0
2014-11-12 10:56 3675float a = 12345; System.out.p ...
相关推荐
总的来说,Servlet3.0通过增强的注解配置、异步处理、过滤器改进、上下文参数和监听器的注解支持,以及微容器概念,极大地提升了Java Web开发的效率和便利性。这份参考手册无疑是深入理解和掌握Servlet3.0技术的关键...
综上所述,这个"Servlet 3.0异步推送聊天室"项目展示了如何利用Servlet 3.0的异步处理和推送技术构建一个实时交互的应用。通过理解和实践这些技术,开发者可以构建出更加高效、响应迅速的Web应用程序。
Servlet 3.0的异步处理则可以配合WebSocket提供更优的解决方案。WebSocket是一种在单个TCP连接上进行全双工通信的协议,它允许服务器主动向客户端推送数据,非常适合实现聊天室这样的实时应用。 创建WebSocket连接...
在压缩包文件`CometTest`中,可能包含了一个简单的Comet实现示例,你可以通过学习和运行这个例子来深入理解Servlet3.0异步处理和Comet页面推送的工作原理。通过实践,你可以更好地掌握如何在实际项目中利用这些技术...
2. **异步处理**:Servlet 3.0引入了异步Servlet的概念,允许Servlet在处理请求时返回控制权给容器,然后在准备好响应时再重新获取控制权。这提高了性能,因为线程可以在等待I/O操作完成时被重用,而不是阻塞等待。 ...
下载的`servlet3.0jar综合`压缩包包含了实现这些特性的关键库,对于进行Java EE 3.0开发的程序员来说是必不可少的工具。在实际开发中,结合相关的框架(如Spring MVC)和其他Java EE组件,可以构建出功能强大、易...
这个压缩包“servlet3.0.zip”包含两个核心的JAR文件:“javax.servlet-javadoc.jar”和“javax.servlet.jar”,它们分别提供了Servlet API的文档和实现。 1. **Servlet API**: - `javax.servlet`包是Servlet API...
【标题】"Jsp/Servlet3.0 ppt和代码"涉及的是Java服务器页面(JSP)和Servlet 3.0版本的关键技术。JSP是一种动态网页技术,它允许开发者将HTML代码与Java代码混合编写,从而实现服务器端的动态内容生成。而Servlet是...
2. **异步处理**:Servlet3.0支持异步处理,允许Servlet在接收到请求后启动一个后台线程进行处理,而主线程可以立即返回,提高了服务器对高并发请求的响应能力。通过`HttpServletRequest.startAsync()`方法,开发者...
在实际开发中,将这些库导入到项目中,开发者可以利用Servlet3.0的异步处理能力,处理高并发场景下的请求;使用JSTL简化页面逻辑,提升开发效率。同时,由于不再依赖web.xml进行所有配置,项目的部署和扩展也变得...
2. **异步处理**:Servlet 3.0引入了异步处理能力,允许Servlet在处理请求时启动一个后台线程,从而提高服务器性能。通过实现`AsyncContext`接口,开发者可以控制请求的生命周期,直到准备好返回响应。 3. **...
在这个版本中,重点强调了异步处理和反向Ajax的支持,这两个特性使得Web应用能够更加高效地处理高并发场景,并提供了更好的用户体验。 一、Servlet3.0的异步支持 1. **异步Servlet**: 在Servlet 3.0之前,Servlet...
1. **异步处理**:Servlet 3.0引入了异步处理能力,允许Servlet在请求处理过程中挂起并稍后恢复,而不是阻塞线程,这极大地提高了应用的并发性能。通过`AsyncContext`接口,开发者可以实现非阻塞I/O,以更高效地处理...
Servlet3.0引入了异步处理能力,允许Servlet在处理请求时返回控制权给容器,然后在后台继续执行任务。通过实现`AsyncContext`,开发者可以创建非阻塞的应用,提高应用性能和响应速度。 3. **Pluggable Contexts**...
总结起来,"servlet3.0-demo"项目展示了Servlet 3.0的关键特性,包括使用注解声明Servlet、处理文件上传以及异步处理。这些改进极大地提升了开发效率,使得Servlet API更加现代化和易于使用。通过学习这个示例,...
2. **异步处理**: Servlet 3.0允许开发者编写异步Servlet,通过`AsyncContext`对象实现非阻塞I/O,提高应用性能。 3. **监听器和过滤器**: 可以使用注解`@WebListener`和`@WebFilter`声明监听器和过滤器,简化了配置...
总结起来,Servlet 3.0提供了更高效、更灵活的Web服务开发方式,通过注解、异步处理、过滤器和依赖注入等功能,让开发者能够编写出更简洁、更强大的Java Web应用。结合AJAX技术,可以构建出响应式、用户体验良好的...
Servlet3.0提供了异步处理能力,允许Servlet在处理请求时启动一个独立的线程,从而避免阻塞容器线程。通过`AsyncContext`接口,可以实现非阻塞I/O和长时间运行的任务。 3. **监听器的注解注册**: 类似于Servlet...
本文将详细介绍 Servlet 3.0 的关键新特性,包括异步处理、新增的注解支持以及可插性支持等方面。 #### 异步处理支持 异步处理是 Servlet 3.0 中最为显著的新特性之一。这一特性解决了传统 Servlet 在处理长时间...