参看网上的springmvc异步支持的小例子,自己试了一下,使用ajax的请求处理方法如下:
@RequestMapping("/response-body")
public @ResponseBody Callable<String> responseBody(){
return new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(2000);
return "Callable result";
}
};
}
但是在调用时出错:
Servlet.service() for servlet [springmvc] in context with path [/SpringMVC_Demo] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding "<async-supported>true</async-supported>" to servlet and filter declarations in web.xml.] with root cause
java.lang.IllegalStateException: Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding "<async-supported>true</async-supported>" to servlet and filter declarations in web.xml.
但是自己也确实在web.xml中加入了异步支持
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!-- springmvc的异步支持 -->
<async-supported>true</async-supported>
</servlet>
仔细一看,报错提示有“filter declarations“ ,难道filter也要修改一下?
我的项目是用的以前练习时的项目,其中使用了springmvc的encoding-filter,为了验证猜想,将filter暂时注释掉,结果没再出错,说明对filter的使用也要加以异步支持声明。
现在在servlet和filter中也加入异步支持,即在每个filter中加入<async-supported>true</async-supported>,再次重启,访问,也不会报错了。
参考:http://www.blogjava.net/yongboy/archive/2011/01/15/346203.html
http://wiselyman.iteye.com/blog/2215852
之后补充:项目中如果引入activemq-all.jar的包,进行springmvc的异步访问是会报错的。
NoSuchMethodError: org.springframework.core.MethodParameter.getContainingClass()Ljava/lang/Class;
网上说是jar包冲突,更换activemq的版本即可,此点未测试