




已閱讀5頁(yè),還剩7頁(yè)未讀, 繼續(xù)免費(fèi)閱讀
版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
Servlet3.0 新特性 一、 概述Servlet 是 Java EE 規(guī)范體系的重要組成部分,也是 Java 開(kāi)發(fā)人員必須具備的基礎(chǔ)技能, Servlet 3.0 引入的若干重要新特性,包括異步處理、新增的注解支持、可插性支持等,為讀者順利向新版本過(guò)渡掃清障礙。Tomcat 支持servlet版本Servlet版本Tomcat版本Jdk最小版本JAVA EE版本Servlet 2.5Tomcat 61.5Java EE5Servlet 3.0Tomcat71.6Java EE6servlet3.0 的新特性包括如下方面:1. 異步處理支持:有了該特性,Servlet 線程不再需要一直阻塞,直到業(yè)務(wù)處理完畢才能再輸出響應(yīng),最后才結(jié)束該 Servlet 線程。在接收到請(qǐng)求之后,Servlet 線程可以將耗時(shí)的操作委派給另一個(gè)線程來(lái)完成,自己在不生成響應(yīng)的情況下返回至容器。針對(duì)業(yè)務(wù)處理較耗時(shí)的情況,這將大大減少服務(wù)器資源的占用,并且提高并發(fā)處理速度。2. 新增的注解支持:該版本新增了若干注解,用于簡(jiǎn)化 Servlet、過(guò)濾器(Filter)和監(jiān)聽(tīng)器(Listener)的聲明,這使得 web.xml 部署描述文件從該版本開(kāi)始不再是必選的了。3. 可插性支持:開(kāi)發(fā)者可以通過(guò)插件的方式很方便的擴(kuò)充已有 Web 應(yīng)用的功能,而不需要修改原有的應(yīng)用。二、 異步處理支持異步處理特性可以應(yīng)用于 Servlet 和過(guò)濾器兩種組件,由于異步處理的工作模式和普通工作模式在實(shí)現(xiàn)上有著本質(zhì)的區(qū)別,因此默認(rèn)情況下,Servlet 和過(guò)濾器并沒(méi)有開(kāi)啟異步處理特性。異步處理關(guān)鍵是在于將復(fù)雜業(yè)務(wù)處理另外開(kāi)一個(gè)線程,而Servlet將執(zhí)行好的業(yè)務(wù)先送往jsp輸出,等到耗時(shí)業(yè)務(wù)做完后再送往JSP頁(yè)面,即先顯示一部分,好事業(yè)務(wù)處理完后再顯示一部分。1. 對(duì)于使用傳統(tǒng)的部署描述文件 (web.xml) 配置 Servlet 和過(guò)濾器的情況,Servlet 3.0 為 和 標(biāo)簽增加了 子標(biāo)簽,該標(biāo)簽的默認(rèn)取值為 false,要啟用異步處理支持,則將其設(shè)為 true 即可。以 Servlet 為例,其配置方式如下所示: DemoServlet footmark.servlet.Demo Servlet true 2. 對(duì)于使用 Servlet 3.0 提供的 WebServlet 和 WebFilter 進(jìn)行 Servlet 或過(guò)濾器配置的情況,這兩個(gè)注解都提供了 asyncSupported 屬性,默認(rèn)該屬性的取值為 false,要啟用異步處理支持,只需將該屬性設(shè)置為 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(); /假設(shè)是個(gè)耗時(shí)任務(wù),此時(shí)必須等待 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(進(jìn)入Servlet的時(shí)間: + new Date() + .); out.flush(); /在子線程中執(zhí)行業(yè)務(wù)調(diào)用,并由其負(fù)責(zé)輸出響應(yīng),主線程退出 AsyncContext ctx = req.startAsync();/設(shè)置超時(shí)時(shí)間 asyncContext.setTimeout(10L * 1000); /開(kāi)始任務(wù) /new Thread(new Executor(ctx).start();/ ctx.start(new Executor(ctx);/這樣也可以 out.println(結(jié)束Servlet的時(shí)間: + 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è)務(wù)方法的執(zhí)行 Thread.sleep(10000); PrintWriter out = ctx.getResponse().getWriter(); out.println(業(yè)務(wù)處理完畢的時(shí)間: + new Date() + .); out.flush(); plete(); catch (Exception e) e.printStackTrace(); 除此之外,Servlet 3.0 還為異步處理提供了一個(gè)監(jiān)聽(tīng)器,使用 AsyncListener 接口表示。它可以監(jiān)控如下四種事件:l 異步線程開(kāi)始時(shí),調(diào)用 AsyncListener 的 onStartAsync(AsyncEvent event) 方法;l 異步線程出錯(cuò)時(shí),調(diào)用 AsyncListener 的 onError(AsyncEvent event) 方法;l 異步線程執(zhí)行超時(shí),則調(diào)用 AsyncListener 的 onTimeout(AsyncEvent event) 方法;l 異步執(zhí)行完畢時(shí),調(diào)用 AsyncListener 的 onComplete(AsyncEvent event) 方法;監(jiān)聽(tīng)器例子: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 的頂層標(biāo)簽 有一個(gè) metadata-complete 屬性,該屬性指定當(dāng)前的部署描述文件是否是完全的。metadata-complete默認(rèn)值為false。如果設(shè)置為 true,則容器在部署時(shí)將只依賴(lài)部署描述文件,忽略所有的注解。1. WebServletWebServlet 用于將一個(gè)類(lèi)聲明為 Servlet,該注解將會(huì)在部署時(shí)被容器處理,容器將根據(jù)具體的屬性配置將相應(yīng)的類(lèi)部署為 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該注解不單獨(dú)使用,而是配合 WebServlet 或者 WebFilter 使用。它的作用是為 Servlet 或者過(guò)濾器指定初始化參數(shù),這等價(jià)于 web.xml 中 和 的 子標(biāo)簽。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 用于將一個(gè)類(lèi)聲明為過(guò)濾器。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該注解用于將類(lèi)聲明為監(jiān)聽(tīng)器,被 WebListener 標(biāo)注的類(lèi)必須實(shí)現(xiàn)以下至少一個(gè)接口: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 提供的對(duì)上傳文件的支持。該注解標(biāo)注在 Servlet 上面,以表示該 Servlet 希望處理的請(qǐng)求的 MIME 類(lèi)型是 multipart/form-data。常用屬性:四、 文件上傳的支持對(duì)于處理上傳文件的操作一直是讓開(kāi)發(fā)者頭疼的問(wèn)題,因?yàn)?Servlet 本身沒(méi)有對(duì)此提供直接的支持,需要使用第三方框架來(lái)實(shí)現(xiàn),而且使用起來(lái)也不夠簡(jiǎn)單。如今這都成為了歷史,Servlet 3.0 已經(jīng)提供了這個(gè)功能,而且使用也非常簡(jiǎn)單。上傳要用到MultipartConfig注解。MultipartConfig常用屬性:例子1:MultipartConfig( location = D:Backup, /即默認(rèn)為 javax.servlet.context.tempdir 如mvn jetty:run 在chapter4targettmp中 maxRequestSize = 1024 * 1024 * 2, /指定一次請(qǐng)求最大的上傳數(shù)據(jù)量(上傳的總和) 單位:字節(jié), -1表示不限制 maxFileSize = 1024 * 1024 * 1, /設(shè)定單個(gè)文件的最大大小,-1表示不限制 fileSizeThreshold = 100000 /當(dāng)上傳的文件大小大于該值時(shí)才寫(xiě)入文件)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); /寫(xiě)到相對(duì)于 MultipartConfig中的location位置 part.write(a.txt); /上傳的文件會(huì)重命名為最后一次的文件名 part.write(b.txt); /調(diào)用完InputStream記得關(guān)閉,否則刪除不掉 InputStream is = part.getInputStream(); is.close(); /不能 part.getInputStream().close();/相當(dāng)于多次獲取 /刪除相關(guān)的文件 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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 人防經(jīng)費(fèi)報(bào)告范文
- 2025年度銀行資金監(jiān)管與合規(guī)性評(píng)估專(zhuān)項(xiàng)協(xié)議
- 2025年度股權(quán)代持股權(quán)繼承協(xié)議書(shū):OO股東代持PP公司股權(quán)的繼承合同
- 二零二五年度實(shí)習(xí)生實(shí)習(xí)期間實(shí)習(xí)成果獎(jiǎng)勵(lì)合同
- 二零二五年度倉(cāng)儲(chǔ)貨物保險(xiǎn)及索賠服務(wù)合同
- 2025年度餐廳裝修合同(含餐廳燈光設(shè)計(jì)與氛圍營(yíng)造)
- 2025年度高科技企業(yè)員工年勞動(dòng)合同
- 2025年度美團(tuán)外賣(mài)平臺(tái)食品安全代運(yùn)營(yíng)合作協(xié)議
- 貨代公司知識(shí)培訓(xùn)課件
- 2025黑龍江中鐵特貨物流股份有限公司招聘75人筆試參考題庫(kù)附帶答案詳解
- 三、種植芽苗菜(教學(xué)設(shè)計(jì))魯科版二年級(jí)下冊(cè)綜合實(shí)踐活動(dòng)
- 2025屆東北師大附屬中學(xué)高考物理五模試卷含解析
- 父母買(mǎi)房在子女名下協(xié)議書(shū)范本
- 項(xiàng)目投資計(jì)算分析表系統(tǒng)(共有17張表格)excel格式
- DBJ15 31-2016建筑地基基礎(chǔ)設(shè)計(jì)規(guī)范(廣東省標(biāo)準(zhǔn))
- 高危新生兒管理專(zhuān)家共識(shí)解讀
- 廣東省深圳市2024年重點(diǎn)中學(xué)小升初數(shù)學(xué)入學(xué)考試卷含解析
- 2023北師大版新教材高中數(shù)學(xué)必修第一冊(cè)考前必背
- JB-T 14426-2023 往復(fù)式氣液混輸泵裝置
- 2024核桃樹(shù)承包合同
- 保險(xiǎn)授權(quán)書(shū)格式模板
評(píng)論
0/150
提交評(píng)論