Servlet3.0 新特性.doc_第1頁
Servlet3.0 新特性.doc_第2頁
Servlet3.0 新特性.doc_第3頁
Servlet3.0 新特性.doc_第4頁
Servlet3.0 新特性.doc_第5頁
已閱讀5頁,還剩7頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領

文檔簡介

Servlet3.0 新特性 一、 概述Servlet 是 Java EE 規(guī)范體系的重要組成部分,也是 Java 開發(fā)人員必須具備的基礎技能, Servlet 3.0 引入的若干重要新特性,包括異步處理、新增的注解支持、可插性支持等,為讀者順利向新版本過渡掃清障礙。Tomcat 支持servlet版本Servlet版本Tomcat版本Jdk最小版本JAVA EE版本Servlet 2.5Tomcat 61.5Java EE5Servlet 3.0Tomcat71.6Java EE6servlet3.0 的新特性包括如下方面:1. 異步處理支持:有了該特性,Servlet 線程不再需要一直阻塞,直到業(yè)務處理完畢才能再輸出響應,最后才結束該 Servlet 線程。在接收到請求之后,Servlet 線程可以將耗時的操作委派給另一個線程來完成,自己在不生成響應的情況下返回至容器。針對業(yè)務處理較耗時的情況,這將大大減少服務器資源的占用,并且提高并發(fā)處理速度。2. 新增的注解支持:該版本新增了若干注解,用于簡化 Servlet、過濾器(Filter)和監(jiān)聽器(Listener)的聲明,這使得 web.xml 部署描述文件從該版本開始不再是必選的了。3. 可插性支持:開發(fā)者可以通過插件的方式很方便的擴充已有 Web 應用的功能,而不需要修改原有的應用。二、 異步處理支持異步處理特性可以應用于 Servlet 和過濾器兩種組件,由于異步處理的工作模式和普通工作模式在實現(xiàn)上有著本質(zhì)的區(qū)別,因此默認情況下,Servlet 和過濾器并沒有開啟異步處理特性。異步處理關鍵是在于將復雜業(yè)務處理另外開一個線程,而Servlet將執(zhí)行好的業(yè)務先送往jsp輸出,等到耗時業(yè)務做完后再送往JSP頁面,即先顯示一部分,好事業(yè)務處理完后再顯示一部分。1. 對于使用傳統(tǒng)的部署描述文件 (web.xml) 配置 Servlet 和過濾器的情況,Servlet 3.0 為 和 標簽增加了 子標簽,該標簽的默認取值為 false,要啟用異步處理支持,則將其設為 true 即可。以 Servlet 為例,其配置方式如下所示: DemoServlet footmark.servlet.Demo Servlet true 2. 對于使用 Servlet 3.0 提供的 WebServlet 和 WebFilter 進行 Servlet 或過濾器配置的情況,這兩個注解都提供了 asyncSupported 屬性,默認該屬性的取值為 false,要啟用異步處理支持,只需將該屬性設置為 true 即可。以 WebFilter 為例,其配置方式如下所示:WebFilter(urlPatterns = /demo,asyncSupported = true) public class DemoFilter implements Filter.同步情況例子:WebServlet(name = syncServlet1, urlPatterns = /sync1)public class SyncServlet1 extends HttpServlet Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException resp.setHeader(Connection, Keep-Alive); resp.setHeader(Proxy-Connection, Keep-Alive); resp.setContentType(text/html;charset=utf-8); PrintWriter out = resp.getWriter(); out.write(hello sync); out.write(); out.flush(); /假設是個耗時任務,此時必須等待 try Thread.sleep(2L * 1000); catch (InterruptedException e) e.printStackTrace(); out.write(over); 模擬異步處理的 Servlet 示例:WebServlet(urlPatterns = /demo, asyncSupported = true)public class AsyncDemoServlet extends HttpServlet Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException resp.setContentType(text/html;charset=UTF-8); PrintWriter out = resp.getWriter(); out.println(進入Servlet的時間: + new Date() + .); out.flush(); /在子線程中執(zhí)行業(yè)務調(diào)用,并由其負責輸出響應,主線程退出 AsyncContext ctx = req.startAsync();/設置超時時間 asyncContext.setTimeout(10L * 1000); /開始任務 /new Thread(new Executor(ctx).start();/ ctx.start(new Executor(ctx);/這樣也可以 out.println(結束Servlet的時間: + new Date() + .); out.flush(); public class Executor implements Runnable private AsyncContext ctx = null; public Executor(AsyncContext ctx) this.ctx = ctx; public void run() try /等待十秒鐘,以模擬業(yè)務方法的執(zhí)行 Thread.sleep(10000); PrintWriter out = ctx.getResponse().getWriter(); out.println(業(yè)務處理完畢的時間: + new Date() + .); out.flush(); plete(); catch (Exception e) e.printStackTrace(); 除此之外,Servlet 3.0 還為異步處理提供了一個監(jiān)聽器,使用 AsyncListener 接口表示。它可以監(jiān)控如下四種事件:l 異步線程開始時,調(diào)用 AsyncListener 的 onStartAsync(AsyncEvent event) 方法;l 異步線程出錯時,調(diào)用 AsyncListener 的 onError(AsyncEvent event) 方法;l 異步線程執(zhí)行超時,則調(diào)用 AsyncListener 的 onTimeout(AsyncEvent event) 方法;l 異步執(zhí)行完畢時,調(diào)用 AsyncListener 的 onComplete(AsyncEvent event) 方法;監(jiān)聽器例子:AsyncContext ctx = req.startAsync(); ctx.addListener(new AsyncListener() Overridepublic void onComplete(AsyncEvent event) throws IOException / TODO Auto-generated method stubSystem.out.println(-complitet-);Overridepublic void onTimeout(AsyncEvent event) throws IOException / TODO Auto-generated method stubOverridepublic void onStartAsync(AsyncEvent event) throws IOException / TODO Auto-generated method stubOverridepublic void onError(AsyncEvent event) throws IOException / TODO Auto-generated method stub);三、 新增注解支持Servlet3.0新增了WebServlet、WebFilter、WebListener、WebInitParam、MultipartConfig注解。Servlet 3.0 的部署描述文件 web.xml 的頂層標簽 有一個 metadata-complete 屬性,該屬性指定當前的部署描述文件是否是完全的。metadata-complete默認值為false。如果設置為 true,則容器在部署時將只依賴部署描述文件,忽略所有的注解。1. WebServletWebServlet 用于將一個類聲明為 Servlet,該注解將會在部署時被容器處理,容器將根據(jù)具體的屬性配置將相應的類部署為 Servlet。WebServlet 主要屬性列表:例子:WebServlet(name = servlet1, urlPatterns = /s1, /s1/*, loadOnStartup = 1)public class Servlet1 extends HttpServlet private String msg; public Servlet1() System.out.println(load on startup); Override public void init() throws ServletException super.init(); msg = this.getInitParameter(msg); Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException System.out.println(msg); 2. WebInitParam該注解不單獨使用,而是配合 WebServlet 或者 WebFilter 使用。它的作用是為 Servlet 或者過濾器指定初始化參數(shù),這等價于 web.xml 中 和 的 子標簽。WebInitParam常用屬性。例子:WebServlet(urlPatterns=/annoServlet,initParams=WebInitParam(name=msg,value=hello world),loadOnStartup=1)public class AnnoServlet extends HttpServlet private static final long serialVersionUID = 1L; /* * see HttpServlet#HttpServlet() */ public AnnoServlet() super(); / TODO Auto-generated constructor stub。Overridepublic void init(ServletConfig config) throws ServletException / TODO Auto-generated method stubsuper.init(config);String msg = config.getInitParameter(msg);System.out.println(-+msg);3. WebFilterWebFilter 用于將一個類聲明為過濾器。WebFilter 的常用屬性:例子:WebFilter(filterName = filter1, urlPatterns=/*, dispatcherTypes = DispatcherType.REQUEST, DispatcherType.FORWARD)public class Filter1 implements Filter Override public void init(final FilterConfig filterConfig) throws ServletException Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException HttpServletRequest httpServletRequest = (HttpServletRequest) request; System.out.println(filter1= + httpServletRequest.getRequestURI(); chain.doFilter(request, response); Override public void destroy() 4. WebListener該注解用于將類聲明為監(jiān)聽器,被 WebListener 標注的類必須實現(xiàn)以下至少一個接口:l ServletContextListenerl ServletContextAttributeListenerl ServletRequestListenerl ServletRequestAttributeListenerl HttpSessionListenerl HttpSessionAttributeListenerWebListener 的常用屬性:例子:WebListenerpublic class ServletContextListener1 implements ServletContextListener Override public void contextInitialized(final ServletContextEvent sce) System.out.println(init servlet context); Override public void contextDestroyed(final ServletContextEvent sce) System.out.println(destroy servlet container); 5. MultipartConfig該注解主要是為了輔助 Servlet 3.0 中 HttpServletRequest 提供的對上傳文件的支持。該注解標注在 Servlet 上面,以表示該 Servlet 希望處理的請求的 MIME 類型是 multipart/form-data。常用屬性:四、 文件上傳的支持對于處理上傳文件的操作一直是讓開發(fā)者頭疼的問題,因為 Servlet 本身沒有對此提供直接的支持,需要使用第三方框架來實現(xiàn),而且使用起來也不夠簡單。如今這都成為了歷史,Servlet 3.0 已經(jīng)提供了這個功能,而且使用也非常簡單。上傳要用到MultipartConfig注解。MultipartConfig常用屬性:例子1:MultipartConfig( location = D:Backup, /即默認為 javax.servlet.context.tempdir 如mvn jetty:run 在chapter4targettmp中 maxRequestSize = 1024 * 1024 * 2, /指定一次請求最大的上傳數(shù)據(jù)量(上傳的總和) 單位:字節(jié), -1表示不限制 maxFileSize = 1024 * 1024 * 1, /設定單個文件的最大大小,-1表示不限制 fileSizeThreshold = 100000 /當上傳的文件大小大于該值時才寫入文件)WebServlet(name = uploadServlet2, urlPatterns = /upload2)public class UploadServlet2 extends HttpServlet Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException Part part = req.getPart(file1); /寫到相對于 MultipartConfig中的location位置 part.write(a.txt); /上傳的文件會重命名為最后一次的文件名 part.write(b.txt); /調(diào)用完InputStream記得關閉,否則刪除不掉 InputStream is = part.getInputStream(); is.close(); /不能 part.getInputStream().close();/相當于多次獲取 /刪除相關的文件 part.delete(); 例子2:MultipartConfig(fileSizeThreshold = 1024 * 1024, location = d:/temp, maxFileSize = 1024 * 1024, maxRequestSize = 2* 1024 * 1024)WebServlet(/UploadServlet2)public class UploadServlet2 extends HttpServlet private static final long serialVersionUID = 1L;public UploadServlet2() super();protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException request.setCharacterEncoding(utf-8);Part file1 = request.getPart(file1);String fileDesposit = file1.getHeader(content-disposition);String fileName = fileDesposit.substring(fileDesposit.lastIndexOf(=) + 2, fileDesposit.length() - 1);/ 文件保存/file1.write(c.txt);/ 保存到其他目錄1/*FileOutputStream fos = new FileOutputStream(new File(request.getServletContext().getRealPath() +File.separator+ fileName);InputStream fis = file1.getInputStream(

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論