1. 程式人生 > >springmvc 配置異步請求

springmvc 配置異步請求

項目 inf cfi sys val pid opera str attr

最開始按照網上配置了一個servlet class 沒有繼承Filter .結果報錯.網上有文章說是tomcat 啟動加載的servlet-3.0- api 加載了 tomcat 安裝目錄下lib裏邊的自帶的 servlet api 與 環境中api沖突 改成

<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>

問題是配置文件裏配置就是這樣的

嚴重: Exception starting filter AsyncFilter
java.lang.ClassCastException: com.AsynDemo.AsynServ cannot be cast to javax.servlet.Filter
這個錯誤其實是沒有繼承Filter,重寫一個過濾導致的

環境:

技術分享圖片

技術分享圖片

pom.xml

<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>

web.xml 配置

這個是把你重寫的過濾類寫入
<filter> <filter-name>pageResponse</filter-name> <filter-class>com.AsynDemo.AsynServlet</filter-class> <async-supported>true</async-supported> </filter> <filter-mapping> <filter-name>pageResponse</filter-name> <!-- 需要註意的是url-parttern 下面的這個路徑項目名稱是不需要寫的直接以 "
/" 代替 --> <url-pattern>/*</url-pattern> </filter-mapping>

<servlet>
<servlet-name>applicationContext</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-common.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported> //
</servlet>


@Controller
@RequestMapping("/asyncServlet")
public class AsynServlet implements Filter
{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub

}


@RequestMapping(value="/testAsyn")
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
System.out.println("start");
PrintWriter out = response.getWriter();
AsyncContext asyncContext = request.startAsync();
asyncContext.setTimeout(5000);
asyncContext.addListener(new MyAsyncListener());
new Thread(new Work(asyncContext,request)).start();
out.print("異步執行中");

}
@Override
public void destroy() {
// TODO Auto-generated method stub

}

}

 

就這麽樣了 還會報錯

A filter or servlet of the current chain does not support asynchronous opera

request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);

查了查資料,

所有的解決辦法都在說可能是參數配置未配置正確,或者是需要在server.xml上配置。最後,在StackOverflow上找到了如下答案

request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);

嘗試這個改了改,問題解決

總結一下,這種配置文件的方式 .坑不少,但最終解決了.

還有一種寫法有空再測試

https://blog.csdn.net/zxaini2010/article/details/50358763

springmvc 配置異步請求