Servlet3發布好幾年了,又有多少人知道它的新特性呢?下面簡單介紹下。
主要增加了以下特性:
1、異步處理支持
2、可插性支持
3、注解支持,零配置,可不用配置web.xml
...
異步處理是什么鬼?
直接操起鍵盤干。
@WebServlet(name = "index", urlPatterns = { "/" }, asyncSupported = true)
public class IndexServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
try {
PrintWriter out = resp.getWriter();
out.println("servlet started.<br/>");
out.flush();
AsyncContext asyncContext = req.startAsync();
asyncContext.addListener(getListener());
asyncContext.start(new IndexThread(asyncContext));
out.println("servlet end.<br/>");
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 異步線程結果監聽
* @author javastack
* @return
*/
private AsyncListener getListener() {
return new AsyncListener() {
public void onComplete(AsyncEvent asyncEvent) throws IOException {
asyncEvent.getSuppliedResponse().getWriter().close();
System.out.println("thread completed.");
}
public void onError(AsyncEvent asyncEvent) throws IOException {
System.out.println("thread error.");
}
public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
System.out.println("thread started.");
}
public void onTimeout(AsyncEvent asyncEvent) throws IOException {
System.out.println("thread timeout.");
}
};
}
}
public class IndexThread implements Runnable {
private AsyncContext asyncContext;
public IndexThread(AsyncContext asyncContext) {
this.asyncContext = asyncContext;
}
public void run() {
try {
Thread.sleep(5000);
PrintWriter out = asyncContext.getResponse().getWriter();
out.println("hello servlet3.<br/>");
out.flush();
asyncContext.complete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
訪問localhost:8080/test
頁面首先輸出
servlet started.
servlet end.
過了5秒后再輸出
hello servlet3.
可以看出servlet立馬返回了,但沒有關閉響應流,只是把response響應傳給了線程,線程再繼續輸出,我們可以將比較費資源消耗時間的程序放到異步去做,這樣很大程序上節省了servlet資源。
Springmvc3.2開始也加入了servlet3異步處理這個特性,有興趣的同學可以去研究下。
從上面的servlet注解也可以看出來,servlet3完全解放了web.xml配置,通過注解可以完全代替web.xml配置。
推薦去我的博客閱讀更多:
2.Spring MVC、Spring Boot、Spring Cloud 系列教程
3.Maven、Git、Eclipse、Intellij IDEA 系列工具教程
覺得不錯,別忘了點贊+轉發哦!