




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
第9章基于Servlet的Web開發(fā)Servlet概述由于JSP在被執(zhí)行之前總是被翻譯為Servlet。Servlet是用JavaServletAPI開發(fā)的一種Java類。這些API被包含在javax.Servlet和javax.Servlet.http這兩個(gè)包中創(chuàng)建ServletServlet類名繼承HttpServlet類Servlet實(shí)例名URL路徑HttpServlet編寫自己的Servlet時(shí),繼承javax.servlet.http.HttpServlet類。HttpServlet是抽象類,它的Http處理方法只有定聲明沒有具體實(shí)現(xiàn)。開發(fā)Servlet類,一般需要重寫doGet()或doPost()方法。一個(gè)簡單的ServletpublicclassHelloServletextendsHttpServlet{privatestaticfinalStringCONTENT_TYPE= "text/html;charset=GBK";publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{ … }publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{ …}}實(shí)現(xiàn)doGet()方法//ProcesstheHTTPGetrequestpublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType(CONTENT_TYPE);PrintWriterout=response.getWriter();out.println("<html>");out.println("<head><title>HelloServlet</title></head>");out.println("<bodybgcolor=\"#ffffff\">");out.println("<p>Hello,Servlet!!!</p>");out.println("</body>");out.println("</html>");out.close();}配置web.xml<web-app><servlet> <servlet-name>firstServlet</servlet-name><servlet-class>servlet.HelloServlet</servlet-class></servlet><servlet-mapping><servlet-name>firstServlet</servlet-name><url-pattern>/hello</url-pattern></servlet-mapping></web-app>訪問Servlet地址欄:http://localhost:8080/web/hello
地址端口站點(diǎn)路徑例:使用Servlet在頁面上顯示一個(gè)登錄表單<form>和一個(gè)鏈接<a>。使該表單和鏈接的提交地址指向一個(gè)Servlet。Servlet生命周期publicclassHelloServletextendsHttpServlet{privatestaticfinalStringCONTENT_TYPE="text/html;charset=GBK";
//初始化publicvoidinit()throwsServletException{}
//對Get方法請求響應(yīng)服務(wù)publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{}//對Post方法請求響應(yīng)服務(wù)publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{}
//銷毀publicvoiddestroy(){}}HttpServletRequest接口javax.servlet.http.HttpServletRequest接口類型的對象對應(yīng)JSP中的request內(nèi)置對象。常用方法publicStringgetParameter(Stringparam)publicString[]getParameterValues(Stringparam)publicvoidsetAttribute(Stringattname,Objecto);publicObjectgetAttribute(Stringattname);HttpResponse接口javax.servlet.http.HttpResponse接口類型的對象對應(yīng)JSP中的response內(nèi)置對象。常用方法publicvoidsetContentType(StringcontentType);publicvoidsendRedirect(Stringurl);JSP到Servlet的轉(zhuǎn)化<%@pagecontentType="text/html;charset=GBK"%><html><bodybgcolor="#ffffff"><fontcolor="red"><%intsum=0;for(inti=1;i<=100;i++){sum+=i;}%><p>1到100的連續(xù)和是:<br/><%=sum%></p></font></body></html>SumServletServletContext接口javax.servlet.ServletContext接口類型的對象對應(yīng)JSP中的application內(nèi)置對象。定義ServletContextapp=this.getServletContext();常用方法publicvoidsetAttribute(Stringattname,Objecto)publicObjectgetAttribute(Stringattname)
ServletConfig接口javax.servlet.ServletConfig接口類型的對象對應(yīng)JSP中的config內(nèi)置對象,用于在Servlet初始化時(shí)向Servlet傳遞一些信息。定義ServletConfigconfig=this.getServletConfig();常用方法publicStringgetInitParameter(Stringparaname)WelcomeServlet會(huì)話管理javax.servlet.http.HttpSession接口類型的對象對應(yīng)JSP中的session內(nèi)置對象。定義HttpSessionsession=request.getSession();HttpSessionsession= request.getSession(booleanvalue);常用方法publicvoidsetAttribute(Stringattname,Objecto)publicObjectgetAttribute(Stringattname)LoginServlet會(huì)話管理publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{Stringuname=request.getParameter("uname"); Stringupass=request.getParameter("upass"); Userperson=newUser(); person.setUname(uname); person.setUpass(upass); UserDAOuserDAO=newUserDAOImpl(); booleanflag=userDAO.isExist(person); if(flag){
HttpSessionsession=request.getSession(); session.setAttribute("users",person); response.sendRedirect("index.jsp");}else{ response.sendRedirect("error.jsp"); }}HttpSession接口維護(hù)session狀態(tài)的方法:方法功能getCreationTime()返回第一個(gè)創(chuàng)建會(huì)話的時(shí)間getLastAccessedTime()返回容器最后一次得到有此會(huì)話ID的請求的時(shí)間(毫秒數(shù))setMaxInactiveInterval()對于此會(huì)話,指定客戶請求的最大間隔時(shí)間getMaxInactiveInterval()對應(yīng)次會(huì)話,返回客戶請求的最大間隔時(shí)間(秒數(shù))invalidate()結(jié)束會(huì)話。當(dāng)前存儲(chǔ)在這個(gè)會(huì)話中的所有會(huì)話屬性也會(huì)解除綁定使session失效的幾種方法關(guān)閉瀏覽器setMaxInactiveInterval()invalidate()在web.xml中配置如下:<session-config> <session-timeout>5</session-timeout> </session-config>
定義session超時(shí)時(shí)間間隔,這里以分鐘為單位Servlet異常處理機(jī)制程序式異常處理:try-catch-finally聲明式異常處理HTTP錯(cuò)誤代碼的處理<error><error-code>404</error-code><location>/fileNotFound.html</location></error>Java異常的處理
<error> <exception-type> java.io.FileNotFoundException</exception-type><location>/index.jsp</location></error>Servlet的線程安全問題//線程不安全訪問計(jì)數(shù)publicclassWelcomeServletextendsHttpServlet{privateIntegernum;publicvoidinit()throwsServletException{ ServletConfigconfig=super.getServletConfig();num=Integer.parseInt(config.getInitParameter("count"));}publicvoiddoGet(…)…{…ServletContextapplication=this.getServletContext();Integern=(Integer)application.getAttribute("num");if(n==null){application.setAttribute("num",num);}else{application.setAttribute("num",n+1);}out.print(application.getAttribute("num"));…}Servlet的線程安全問題//線程安全訪問計(jì)數(shù)publicclassWelcomeServletextendsHttpServlet{privateIntegernum;publicvoidinit()throwsServletException{ ServletConfigconfig=super.getServletConfig();num=Integer.parseInt(config.getInitParameter("count"));}publicsynchronizedvoiddoGet(…)…{…ServletContextapplication=this.getServletContext();Integern=(Integer)application.getAttribute("num");if(n==null){application.setAttribute("num",num);}else{application.setAttribute("num",n+1);}out.print(application.getAttribute("num"));…}屬性的線程安全ServletContext對象:不是線程安全的HttpSession對象:不是線程安全的synchronized(session){…}ServletRequest對象:線程安全過濾器過濾器是一個(gè)程序,它先于與之相關(guān)的Servlet或JSP頁面運(yùn)行在服務(wù)器上。過濾器可附加到一個(gè)或多個(gè)Servlet或JSP頁面上,并且可以檢查進(jìn)入這些資源的請求信息。在這之后,過濾器可以作如下的選擇:以常規(guī)的方式調(diào)用資源(即,調(diào)用Servlet或JSP頁面)。利用修改過的請求信息調(diào)用資源。調(diào)用資源,但在發(fā)送響應(yīng)到客戶機(jī)前對其進(jìn)行修改。阻止該資源調(diào)用,代之以轉(zhuǎn)到其他的資源,返回一個(gè)特定的狀態(tài)代碼或生成替換輸出。創(chuàng)建過濾器的步驟建立一個(gè)實(shí)現(xiàn)javax.servlet.Filter接口的類在doFilter方法中放入過濾行為調(diào)用FilterChain對象的doFilter方法對相應(yīng)的Servlet和JSP頁面注冊過濾器過濾器應(yīng)用實(shí)例——解決請求數(shù)據(jù)中文亂碼問題
建立一個(gè)實(shí)現(xiàn)Filter接口的類EncodingCharacterFilter:publicclassEncodingCharacterFilterimplementsFilter{…publicvoiddoFilter( ServletRequestrequest,ServletResponseresponse,FilterChainchain)throwsIOException,ServletException{request.setCharacterEncoding("GB2312");chain.doFilter(request,response);}…}過濾器應(yīng)用實(shí)例——解決請求數(shù)據(jù)中文亂碼問題注冊過濾器<filter><filter-name>EncodingCharacterFilter</filter-name><filter-class>filter.EncodingCharacterFilter</filter-class></filter><filter-mapping><filter-name>EncodingCharacterFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>過濾器應(yīng)用實(shí)例——身份驗(yàn)證問題
建立一個(gè)實(shí)現(xiàn)Filter接口的類AuthorizationFilter:publicclassAuthorizationFilterimplementsFilter{publicvoiddoFilter( ServletRe
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 建筑智能化系統(tǒng)設(shè)計(jì)技術(shù)規(guī)范
- 零售業(yè)O2O營銷模式創(chuàng)新與實(shí)施策略
- 綠色建筑材料應(yīng)用技術(shù)規(guī)范書
- 機(jī)器人技術(shù)及其在物流行業(yè)的應(yīng)用手冊
- 哪些項(xiàng)目需要可行性研究報(bào)告批復(fù)
- 生態(tài)農(nóng)業(yè)規(guī)劃方案
- 三農(nóng)項(xiàng)目申報(bào)與實(shí)施全流程作業(yè)指導(dǎo)書
- 醫(yī)院感染防控知識(shí)培訓(xùn)手冊
- 醫(yī)療保健管理與咨詢服務(wù)作業(yè)指導(dǎo)書
- 投融資業(yè)務(wù)助力儲(chǔ)能加速實(shí)現(xiàn)商業(yè)化應(yīng)用
- GB/T 5023.5-2008額定電壓450/750 V及以下聚氯乙烯絕緣電纜第5部分:軟電纜(軟線)
- GB/T 23445-2009聚合物水泥防水涂料
- 瓷貼面教學(xué)課件
- 尺骨冠突骨折課件
- 北師大版七年級下冊第一章整式的乘除計(jì)算題專項(xiàng)訓(xùn)練
- 2022年蘇州健雄職業(yè)技術(shù)學(xué)院單招考試面試試題及答案解析
- 植物生理教案
- 乳腺癌改良根治術(shù)
- 新版(七步法案例)PFMEA
- 臨床護(hù)理重點(diǎn)??平ㄔO(shè)項(xiàng)目評審標(biāo)準(zhǔn)
- 二倍角的三角函數(shù)說課稿
評論
0/150
提交評論