版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
第36講(會話技術(shù)簡介)什么是會話?(會話是針對一種網(wǎng)站而言,不是針對各種網(wǎng)站。)基本概念:指顧客開一種瀏覽器,訪問一種網(wǎng)站,只要不關(guān)閉該瀏覽器,不論該顧客點(diǎn)擊多少個超鏈接,訪問多少資源,直到顧客關(guān)閉瀏覽器,整個這個過程咱們稱為一次會話。例如打電話,只要電話不斷就算一次電話,至于過程中和多少人說過話,說多長時間,都算一次。點(diǎn)一次超鏈接就是一種request,不也許保存起來。因此要用會話來保存數(shù)據(jù)。//——————————————————————————————————————如何保存顧客上次登錄時間如何顯示顧客瀏覽歷史如何把登錄顧客名和密碼保存到電腦,下次登錄,不需要重新輸入解決之道——cookieCookie是客戶端技術(shù),服務(wù)器把每個顧客數(shù)據(jù)以cookie形式寫給顧客各自瀏覽器。當(dāng)顧客使用瀏覽器再去訪問服務(wù)器中web資源時,就會帶著各自數(shù)據(jù)去。這樣,web資源解決就是顧客各自數(shù)據(jù)了。服務(wù)器在客戶端保存顧客信息,例如登錄名,密碼等...就是cookie,這些信息就像是小甜餅同樣,數(shù)據(jù)量并不大,服務(wù)器端在需要時候可以從客戶端讀取,保存在客戶端瀏覽器緩存目錄下。Cookie原理示意圖Cookie創(chuàng)立是在服務(wù)器創(chuàng)立,存儲是在瀏覽器這頭存儲。ClassCookie//——————————————————————————————————————InterfaceHttpServletResponse//——————————————————————————————————————演示Cookie工作publicclassCreateCookieextendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); //創(chuàng)立cookie(api) Cookiecookie=newCookie("name","mingcheng1"); //設(shè)立cookie生命周期 cookie.setMaxAge(3600); //把cookie信息回寫給瀏覽器 response.addCookie(cookie); }//——————————————————————————————————————在ie訪問http://localhost:8888/cookie1/CreateCookie,用HttpWatch抓包得到信息(response):InterfaceHttpServletRequest//——————————————————————————————————————publicclassReadCookie1extendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); //讀取所有cookie信息,再選中你要cookie Cookiecookies[]=request.getCookies(); System.out.println(cookies.length); }//——————————————————————————————————————在ie訪問http://localhost:8888/cookie1/ReadCookie1,用HttpWatch抓包得到信息(request):在控制臺浮現(xiàn)信息://—————————————————————————————————————— for(inti=0;i<cookies.length;i++) { Cookiecookie=cookies[i]; out.println("cookie信息名字="+cookie.getName()+"value="+cookie.getValue()); } }//——————————————————————————————————————cookie原理圖cookie可以用來做什么保存上次登錄時間等信息保存顧客名、密碼,在一定期間不用重新登錄記錄顧客訪問網(wǎng)站喜好(例如有無背景音樂、網(wǎng)頁背景色是什么)網(wǎng)站個性化,例如定制網(wǎng)站服務(wù),內(nèi)容。cookie小結(jié)cookie是在服務(wù)器創(chuàng)立cookie是保存在瀏覽器這端cookie生命周期可以通過cookie.setMaxAge();?如果不設(shè)立setMaxAge則該cookie生命周期當(dāng)瀏覽器關(guān)閉時,就消滅.cookie可以被各種瀏覽器共享怎么理解咱們可以把cookie想成一張表?如果cookie重名會有什么問題?如果重名就會替代存在cookie值.一種web應(yīng)用可以保存各種cookie(各種cookie存儲在一種文獻(xiàn)里,無論生命周期相似不相似)cookie存儲時候是以明文方式存儲,因而安全較低,咱們可以通過加密后保存.->補(bǔ)講一種md5算法:請人們注意,后來咱們密碼都要使用加密存儲,在驗證密碼時候,對顧客輸入密碼,進(jìn)行md5加密,然后再到數(shù)據(jù)庫去驗證//————————————————————————————————————publicclassServlet1extendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); //先獲取cookie //假設(shè)咱們保存上次登錄時間cookie"lasttime""-11-1112:12:12" //這里咱們要考慮一種狀況:顧客第一次登陸'您是第一次登陸...' Cookiecookies[]=request.getCookies(); booleanb=false;//假設(shè)沒有l(wèi)asttimecookie if(cookies!=null)//保證有cookie,才去遍歷 { for(Cookiecookie:cookies) {//取出名 Stringname=cookie.getName(); if("lasttime".equals(name)) {//顯示 out.println("您上次登錄時間是:"+cookie.getValue()); //更新時間 //把當(dāng)前日期保存cookie SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); StringnowTime=simpleDateFormat.format(newjava.util.Date()); cookie.setValue(nowTime); cookie.setMaxAge(7*3600*24);//保存一周 response.addCookie(cookie); b=true; break; } } } if(!b) {//沒有找到 out.println("您是第一次登陸..."); //把當(dāng)前日期保存cookie SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); StringnowTime=simpleDateFormat.format(newjava.util.Date()); Cookiecookie=newCookie("lasttime",nowTime); cookie.setMaxAge(7*3600*24);//保存一周 response.addCookie(cookie); } }//——————————————————————————————————————//——————————————————————————————————————打開登錄頁面時候,自動填寫該顧客顧客名和密碼(最佳單開一種項目)//——————————————————————————————————————//——————————————————————————————————————點(diǎn)擊登錄后再回到Login頁面點(diǎn)擊刷新,顧客id已自動填寫://——————————————————————————————————————點(diǎn)一下商品名,就彈窗商品信息,同步在刷新主界面時候,能顯示出看了哪些商品,并且還要加一種功能,最后看商品要放到最前面去,當(dāng)瀏覽過商品超過了四個后來,只保存四個。//——————————————————————————————————————cookie細(xì)節(jié)①一種瀏覽器最多放入300cookie,一種web站點(diǎn),最多20cookie,并且一種cookie大小限制在4k②cookie生命周期再闡明:1.cookie默認(rèn)生命周期是會話級別2.通過setMaxAge()可以設(shè)立生命周期setMaxAge(正數(shù)),即多少秒后該cookie失效setMaxAge(0),刪除該cookie③cookie存儲中文,怎么解決存儲:Stringval=.URLEncoder.encode("銘城","utf-8");Cookiecookie=newCookie("name",val);取出:Stringval=.URLDecoder.decode(cookie.getValue(),"utf-8");out.println("name="+val);案例://——————————————————————————————————————//——————————————————————————————————————點(diǎn)擊刷新后:特別闡明:如果該web應(yīng)用只有一種cookie,則刪除該cookie后,在瀏覽器暫時文獻(xiàn)夾下沒有該cookie文獻(xiàn),如果該web應(yīng)用有各種cookie,則刪除一種cookie后,文獻(xiàn)還在,只是該cookie沒有setMaxAge(負(fù)數(shù)),相稱于該cookie生命周期是會話級別。//第39講(session技術(shù))=========================================================?張三和李四她們購買商品不同樣,她們購物車中顯示商品也不同樣,這是怎么實現(xiàn)??此外一種問題,不同顧客登錄網(wǎng)站后,不論該顧客瀏覽該網(wǎng)站哪個頁面,都可顯示登錄人名字,同樣可以隨時去查看自己購物車中商品。session為什么有?問題1:如何實當(dāng)前不同頁面,可以去查看信息(例如說購物車),同步還要實現(xiàn)不同顧客看到信息是自己.對session闡明:session是存儲在服務(wù)器內(nèi)存中一種顧客瀏覽器,獨(dú)享一種session域?qū)ο髎ession默認(rèn)生命周期是30minInterfaceHttpSession//——————————————————————————————————————InterfaceHttpServletRequestF:\tomcat\apache-tomcat-8.0.28\conf\web.xml//——————————————————————————————————————publicclassServlet1extendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); //訪問session[當(dāng)發(fā)現(xiàn)沒有session時候,就會自動創(chuàng)立session] HttpSessionsession=request.getSession(); //給該session放入屬性 session.setAttribute("uname","宋江"); //session生命周期(默認(rèn)30min,你也可以修改) out.println("創(chuàng)立session,并放入了一種屬性"); }//————————————————————————————————————publicclassServlet2extendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); //獲取session HttpSessionsession=request.getSession(); //獲取 Stringuname=(String)session.getAttribute("uname"); if(uname==null) { out.println("session中沒有uname"); }else{ out.println("uname="+uname); } }//————————————————————————————————————先訪問Servlet1:再訪問Servlet2,在搜狗和ie瀏覽器中返回成果不同樣,證明了一種顧客瀏覽器,獨(dú)享一種session域?qū)ο?/——————————————————————————————————————?如果同一種顧客瀏覽器,向設(shè)立一種屬性時候,如果名字相似了,會浮現(xiàn)什么狀況?結(jié)論:會替代該對象值。//——————————————————————————————————————演示publicclassServlet3extendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); //訪問session[當(dāng)發(fā)現(xiàn)沒有session時候,就會自動創(chuàng)立session] HttpSessionsession=request.getSession(); session.setAttribute("uname","銘城"); out.println("重新設(shè)立uname"); }//——————————————————————————————————————先訪問Servlet3重新設(shè)立uname再訪問Servlet2,這是uname已經(jīng)變成銘城了。//——————————————————————————————————————request.getSession(true);//和不帶參數(shù)同樣request.getSession(false);//沒有session就算了,不再創(chuàng)立新//——————————————————————————————————————publicclassServlet4extendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); HttpSessionsession=request.getSession(); session.removeAttribute("uname"); out.println("刪除uname"); }//————————————————————————————————————Servlet2->Servlet4->Servlet2//——————————————————————————————————————//——————————————————————————————————————//—————————————————————————————————————— //創(chuàng)立一種對象 Useruser=newUser(); user.setName("小貓"); user.setColor("紅色"); session.setAttribute("cat",user);//———————————————————————————————————— Useruser=(User)session.getAttribute("cat"); if(user!=null) { out.println("貓信息是"+user.getName()+""+user.getColor()); }//————————————————————————————————————Servlet1->Servlet2//——————————————————————————————————————session小結(jié):①session是存在服務(wù)器內(nèi)存中②一種顧客瀏覽器,獨(dú)享一種session域?qū)ο螈踫ession中屬性默認(rèn)生命周期是30min,你可以通過web.xml來修改這樣修改:1)一種地方是tomcat/conf/web.xml對所有web應(yīng)用生效2)此外一種地方,就是在單個web應(yīng)用下去修改web.xml如果發(fā)生沖突,則以自己web應(yīng)用下為準(zhǔn) session.setMaxInactiveInterval(20);//20s指是發(fā)呆時間對session生命周期小結(jié):④session中可以存儲各種屬性⑤session可以存儲對象⑥如果session.setAttribute(“name”,val),如果名字重復(fù),則會替代該屬性//——————————————————————————————————————測試removeAttribute()辦法效果://——————————————————————————————————————小作業(yè):防止顧客非法登錄到某個頁面顧客必要登錄后,才干操作管理頁面。思路:當(dāng)顧客成功登錄后,可以把該顧客信息存儲到session,然后在需要驗證頁面中獲取顧客信息,如果為null,闡明顧客非法,可以讓其重新登錄.//——————————————————————————————————————//——————————————————————————————————————//——————————————————————————————————————在之前LoginServlet寫過request.getAttribute(“...”)接受到錯誤信息//——————————————————————————————————————效果://——————————————————————————————————————如果網(wǎng)站有非常多頁面,可以使用下面辦法封裝成函數(shù)使用過濾器//——————————————————————————————————————session更進(jìn)一步理解:為什么服務(wù)器可覺得不同瀏覽器提供不同session?//——————————————————————————————————————抓包來查看Jsessionid:訪問http://localhost:8888/session1/Servlet1當(dāng)發(fā)現(xiàn)沒有session時候,就會自動創(chuàng)立。訪問http://localhost:8888/session1/Servlet5當(dāng)前在服務(wù)器內(nèi)存已有session,瀏覽器祈求時帶上Cookie(保存有jsessionid),服務(wù)器依照此id來尋找相應(yīng)瀏覽器session。session.getId()用來在頁面上打印jsessionid。.net[開源之祖]3萬各種開源項目電驢、防火墻、殺毒軟件、數(shù)據(jù)庫、大型游戲、地圖c語言、java、php、.net、asp//——————————————————————————————————————驗證碼案例使用(原理是使用到j(luò)ava繪圖技術(shù))這里最重要就是生成驗證碼servlet//——————————————————————————————————————packagecom.wmc;importjava.awt.Color;importjava.awt.Font;importjava.awt.Graphics;importjava.awt.image.BufferedImage;importjava.io.IOException;importjava.io.PrintWriter;importjava.util.Random;importjavax.imageio.ImageIO;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;publicclassCreateCodeextendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{// response.setContentType("text/html;charset=utf-8");// response.setCharacterEncoding("utf-8");// PrintWriterout=response.getWriter(); //7.禁止瀏覽器緩存隨機(jī)圖片 response.setDateHeader("Expires",-1); response.setHeader("Cache-Control","no-cache"); response.setHeader("Pragma","no-cache"); //6.告知客戶機(jī)以圖片方式打開發(fā)送過去數(shù)據(jù) response.setHeader("Content-Type","image/jpeg"); //1.在內(nèi)存中創(chuàng)立一副圖片 BufferedImageimage=newBufferedImage(60,30,BufferedImage.TYPE_INT_RGB); //2.向圖片上寫數(shù)據(jù) Graphicsg=image.getGraphics(); //設(shè)背景色 g.setColor(Color.black); g.fillRect(0,0,60,30); //3.設(shè)立寫入數(shù)據(jù)顏色和字體 g.setColor(Color.red); g.setFont(newFont(null,Font.BOLD,20)); //4.向圖片上寫數(shù)據(jù) Stringnum=makeNum(); //這句話就是把隨機(jī)生成數(shù)值,保存到session request.getSession().setAttribute("checkcode",num); g.drawString(num,0,20); //5.把寫好數(shù)據(jù)圖片輸出給瀏覽器 ImageIO.write(image,"jpg",response.getOutputStream()); } //該函數(shù)是隨機(jī)生成7位數(shù)字 publicStringmakeNum() { Randomr=newRandom(); //9999999可以生成7位 Stringnum=r.nextInt(9999)+""; StringBuffersb=newStringBuffer(); //如果不夠4位,前面補(bǔ)零 for(inti=0;i<4-num.length();i++) { sb.append("0"); } num=sb.toString()+num; returnnum; } publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ this.doGet(request,response); }}//——————————————————————————————————————圖片實質(zhì)上就是一種文獻(xiàn),咱們看電影都是按文獻(xiàn)流來傳播。因此地址寫一種servlet,然后servlet再寫會一種圖片回來。 out.println("<h1>顧客登錄</h1>"); //action應(yīng)當(dāng)這樣寫 /web應(yīng)用名/Servleturl out.println("<formaction='/mycheckcode/LoginCl'method='post'>"); out.println("顧客id:<inputtype='text'name='id'/><br/>"); out.println("密碼:<inputtype='password'name='password'/><br/>"); out.println("驗證碼:<inputtype='text'name='checkcode'/><imgsrc='/mycheckcode/CreateCode'><br/>"); out.println("<inputtype='submit'value='登錄'/><br/>"); out.println("</form>"); Stringerr=(String)request.getAttribute("err"); if(err!=null) { out.println(err); }如何使用:Login.java<imgsrc=”/驗證碼url”/>//—————————————————————————————————————— //獲取顧客id/password/輸入驗證碼 Stringid=request.getParameter("id"); Stringpasswd=request.getParameter("passwd"); Stringcheckcode=request.getParameter("checkcode"); //取出session中驗證碼 Stringcheckcode2=(String)request.getSession().getAttribute("checkcode"); //1.先驗證碼 if(checkcode.equals(checkcode2)) { //驗證碼ok request.getRequestDispatcher("/Ok").forward(request,response); //到數(shù)據(jù)庫去驗證 }else{ request.setAttribute("err","驗證碼錯誤"); request.getRequestDispatcher("/Login").forward(request,response); }//————————————————————————————————————out.println("loginok");//————————————————————————————————————效果:輸入對的驗證碼:輸入錯誤驗證碼:練習(xí),把驗證碼功能加入到顧客管理系統(tǒng)。//過濾器———————————————————————————————————過濾器(filter)①開發(fā)過濾器環(huán)節(jié):創(chuàng)立繼承HttpServlet同步實現(xiàn)Filter接口默認(rèn)filter不生效,需要配備.web.xml:<!--自己配備一種filter/*表達(dá)對該WEB所有網(wǎng)頁都過濾--><filter> <filter-name>MyFilter</filter-name> <filter-class>com.wmc.filter.MyFilter</filter-class></filter><filter-mapping> <filter-name>MyFilter</filter-name> <url-pattern>/*</url-pattern></filter-mapping>3.在filter辦法中添加業(yè)務(wù)邏輯.packagecom.wmc.filter;importjava.io.IOException;importjava.io.PrintWriter;importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importcom.wmc.domain.User;publicclassMyFilterextendsHttpServletimplementsFilter{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); } publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ this.doGet(request,response); } @Override publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse, FilterChainchain)throwsIOException,ServletException{ //TODOAuto-generatedmethodstub //獲取request HttpServletRequesthttpServletRequest=(HttpServletRequest)request; //看看祈求資源是什么 Stringuri=httpServletRequest.getRequestURI(); if(uri.startsWith("/UsersManager3/imgs")||uri.startsWith("/UsersManager3/servlet/Login")||uri.startsWith("/UsersManager3/servlet/CreateCode")) { //如果是祈求到登錄有關(guān)頁面以及圖片驗證碼uri,直接放行 chain.doFilter(request,response); }else{ HttpSessionsession=httpServletRequest.getSession(); Useruser=(User)session.getAttribute("loginuser"); if(user!=null) { //該顧客合法,放行 chain.doFilter(request,response); }else{ request.setAttribute("err","請好好登錄"); httpServletRequest.getRequestDispatcher("/servlet/LoginServlet").forward(request,response); } } } @Override publicvoidinit(FilterConfigfilterConfig)throwsServletException{ //TODOAuto-generatedmethodstub }}過濾器鏈實現(xiàn)方式:在創(chuàng)立一種過濾器(繼承HttpServlet同步還要實現(xiàn)Filter接口)配備過濾器配備過濾器順序就可以決定調(diào)用過濾器順序.Filter執(zhí)行順序與在web.xml配備文獻(xiàn)中配備順序一致,普通把Filter配備在所有Servlet之前。//—————————————————————————————————————————————————————————————————————————對session銷毀時間討論-借助一種案例面試題:(應(yīng)用:關(guān)掉IE后,再開IE,上次購買商品還在,->設(shè)計到session銷毀時間)分析咱們session生命周期如果是30min,該session不會隨瀏覽器關(guān)閉,而自動銷毀,而會到30min后,才會被服務(wù)器銷毀.咱們使用代碼來實現(xiàn)該功能(session+cookie結(jié)合使用)//—————————————————————————————————————— //創(chuàng)立一種session,并放入一種屬性 HttpSessionsession=request.getSession(); session.setAttribute("username","王銘成"); //默認(rèn)30min //把 該sessionid保存cookie,在保存id時,一定要按照 //規(guī)范命名這里區(qū)別大小寫. Cookiecookie=newCookie("JSESSIONID",session.getId()); cookie.setMaxAge(60*30); response.addCookie(cookie);//————————————————————————————————————————————————————————————————————————— //讀取session屬性 Stringuname=(String)request.getSession().getAttribute("username"); out.println("uname="+uname);//—————————————————————————————————————————————————————————————————————————關(guān)閉ie后再開ie,輸入http://localhost:8888/session2/Servlet2,能顯示出uname//—————————————————————————————————————————————————————————————————————————如何實現(xiàn)ie禁用cookie后,咱們還可以繼續(xù)使用session*放到簡易購物車那解說決//第43講(簡易購物車)——————————————————————————————簡易購物車實例:思路:當(dāng)顧客點(diǎn)擊購買商品時,咱們把該商品保存到session中,該session構(gòu)造是:name valmybooks hashMap對象而hashmap構(gòu)造是:key val書號 書對象Book.java類;詳細(xì)實現(xiàn),參看myCart項目總結(jié)咱們使用到有關(guān)知識‘java基本集合ArrayListHashMapLinkedHashMap(有序)session技術(shù)servlet單態(tài)如何選取不同集合 list集合都是有序map集合是無序list和map集合都可以放入nulllist可以放入相似對象,而map也可以放相似對象,但是key不能重復(fù)session中存儲鍵為”mybooks”,值為HashMap對象。HashMap對象中存儲鍵為課本id(String),值為book對象。//——————————————————————————————————————publicclassShowBookextendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); //先死后活 out.println("<h1>歡迎購買</h1>"); out.println("java書<ahref='/myCart/BuyBookCl?id=1&name=java'>點(diǎn)擊購買</a><br/>"); out.println("oracle書<ahref='/myCart/BuyBookCl?id=2&name=oracle'>點(diǎn)擊購買</a><br/>"); out.println("c書<ahref='/myCart/BuyBookCl?id=3&name=c'>點(diǎn)擊購買</a><br/>"); }//——————————————————————————————————————publicclassBuyBookClextendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); Stringbookname=request.getParameter("name"); Stringid=request.getParameter("id"); HttpSessionsession=request.getSession(); //從session中取出mybooks HashMap<String,Book>hm=(HashMap<String,Book>)session.getAttribute("mybooks"); //如果是第一次購物hm=null if(hm==null) { hm=newHashMap<String,Book>(); //創(chuàng)立一種Book對象 Bookbook=newBook(); book.setId(id); book.setName(bookname); book.setNum(1); hm.put(id,book); }else{ //判斷hm中與否有該書 if(hm.containsKey(id)) { //表達(dá)書購買過一次 //取出 Bookbook=hm.get(id); intbookNum=book.getNum(); book.setNum(bookNum+1); }else{ Bookbook=newBook(); book.setId(id); book.setName(bookname); book.setNum(1); hm.put(id,book); } } //更新 session.setAttribute("mybooks",hm); request.getRequestDispatcher("/ShowMyCart").forward(request,response); }//——————————————————————————————————————publicclassShowMyCartextendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); //從session中取出看購買數(shù) HashMap<String,Book>myBooks=(HashMap<String,Book>)request.getSession().getAttribute("mybooks"); out.println("你購物車有如下書籍:<br/>"); //遍歷HashMap Iteratorit=myBooks.keySet().iterator(); while(it.hasNext()) { Stringkey=(String)it.next(); Bookbook=myBooks.get(key); out.println("書名:"+book.getName()+"數(shù)量:"+book.getNum()+"<br/>"); } out.println("<ahref='/myCart/ShowBook'>返回購物大廳</a>"); }//——————————————————————————————————————效果://——————————————————————————————————————用ArrayList模仿一種內(nèi)存數(shù)據(jù)庫:packagecom.wmc;importjava.util.ArrayList;//用arrayList模仿一種內(nèi)存數(shù)據(jù)庫finalpublicclassDB{ privatestaticArrayListal=null; privateDB(){ } static{ al=newArrayList<Book>(); Bookbook1=newBook(); book1.setId("1"); book1.setName("java"); Bookbook2=newBook(); book2.setId("2"); book2.setName("oracle"); Bookbook3=newBook(); book3.setId("3"); book3.setName("c"); Bookbook4=newBook(); book4.setId("4"); book4.setName("linux"); al.add(book1); al.add(book2); al.add(book3); al.add(book4); } publicstaticArrayListgetDB() { returnal; } publicstaticBookgetBookById(Stringid) { Bookbook=null; for(inti=0;i<al.size();i++) { book=(Book)al.get(i); if(book.getId().equals(id)) { returnbook; } } returnnull; }}//——————————————————————————————————————//——————————————————————————————————————//——————————————————————————————————————//——————————————————————————————————————要在購物車中顯示每類書總共價格和所有書總價://——————————————————————————————————————//——————————————————————————————————————//——————————————————————————————————————//——————————————————————————————————————效果://——————————————————————————————————————//——————————————————————————————————————//——————————————————————————————————————
該辦法實現(xiàn)機(jī)制為:
●先判斷當(dāng)前Web組件與否啟用Session,如果沒有啟用Session,直接返回參數(shù)url。
●再判斷客戶端瀏覽器與否支持Cookie,如果支持Cookie,直接返回參數(shù)url;如果不支持Cookie,就在參數(shù)url中加入SessionID信息,然后返回修改后url。
//——————————————————————————————————————cookievssession①存在位置cookie:存在客戶端暫時文獻(xiàn)夾session:存在服務(wù)器內(nèi)存中,一種session域?qū)ο鬄橐环N顧客瀏覽器服務(wù)②安全性cookie是以明文方式存儲在客戶端,安全弱,可以通過加密md5再存儲session是存儲在服務(wù)器內(nèi)存中,因此安全性好③網(wǎng)絡(luò)傳播量cookie會傳遞信息,給服務(wù)器session屬性值不會給客戶端④生命周期cookie生命周期是合計時間:即如果咱們給cookie設(shè)立setMaxAge(30)則30s后失效session生命周期是間隔時間,如咱們設(shè)立session20min,指在20min內(nèi),如果沒有訪問session,則session失效(含義是指無法取出session屬性),在如下狀況session也會失效關(guān)閉tomcatreloadweb應(yīng)用時間到invalidate也會讓session失效⑤使用原則由于session會占用服務(wù)器內(nèi)存,因而不要向session存儲過多,過大對象,會影響性能.//第45講(ServletContext)===============================================為什么需要servletContext需求1需求2解決之道——ServletContext原理圖:迅速入門ServletContextServletContext是在服務(wù)器ServletContext是被所有客戶端共享ServletContext是當(dāng)web應(yīng)用啟動時候,自動創(chuàng)立ServletContext當(dāng)web應(yīng)用關(guān)閉/tomcat關(guān)閉/對web應(yīng)用reload會導(dǎo)致servletContext銷毀.//——————————————————————————————————————publicclassServlet1extendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); //獲取ServletContext對象引用 //1.通過this直接獲取. ServletContextservletContext=this.getServletContext(); //2.通過ServletConfig獲取 //ServletContextservletContext2=this.getServletConfig().getServletContext(); servletContext.setAttribute("uname","王銘成"); out.println("寫入一種屬性到servletContext"); }//—————————————————————————————————————— publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); //取出ServletContext某個屬性 //1.一方面獲取到ServletContext ServletContextservletContext=this.getServletContext(); //2.取出屬性,這個屬性值,相應(yīng)什么類型就應(yīng)當(dāng)轉(zhuǎn)成什么類型 Stringval=(String)servletContext.getAttribute("uname"); out.println("val="+val); }//——————————————————————————————————————成果:訪問http://localhost:8888/serContext/Servlet1后,再用此外瀏覽器如搜狗,百度瀏覽器,訪問。MyEclipse自帶瀏覽器:搜狗瀏覽器:百度瀏覽器://——————————————————————————————————————對ServletContext用法小結(jié)獲?。簍his.getServletContext();this.getServletConfig().getServletContext();添加屬性:servletContext.setAttribute(string,object);取出屬性:servletContext.getAttribute("屬性名");刪除:servletContext.removeAttribute("屬性名");//————————————————————————————————————ServletContext應(yīng)用獲取WEB應(yīng)用初始化參數(shù)在web.xml中<!--如果但愿所有servlet都可以訪問該配備.--><context-param> <param-name>username</param-name><param-value>scott</param-value></context-param>如何獲???Stringval=this.getServletContext().getInitParameter("username");*只能給單個servlet訪問參數(shù)配備辦法使用ServletContext實現(xiàn)跳轉(zhuǎn) //當(dāng)前咱們跳轉(zhuǎn)到下一種頁面 //1response.sendRedirect("/web應(yīng)用名/資源名"); //2request.getRequestDispatcher("/資源名").forward(request,response); /** *區(qū)別 1. getRequestDispatcher跳轉(zhuǎn)發(fā)生在web服務(wù)器 sendRedirect發(fā)生在瀏覽器 * 2. 如果request.setAttribute("name","wmc")但愿下一種頁面可以使用name屬性值, * 則使用getRequestDispatcher * 3. 如果session.setAttribute("name2","wmc2"),但愿下一種頁面可以使用name2屬性值, * 則兩個辦法均可使用,但是建議使用getRequestDispatcher * 4. 如果咱們但愿跳轉(zhuǎn)到本web應(yīng)用外一種url,應(yīng)使用sendRedirect */ //3這種辦法和2同樣 this.getServletContext().getRequestDispatcher("/資源url").forward(request,response);運(yùn)用ServletContext對象讀取資源文獻(xiàn)在WebRoot下建立一種資源文獻(xiàn)(perties) 屬性以及屬性值:成功讀到資源文獻(xiàn)中屬性:*如果文獻(xiàn)放在src目錄下,則使用類加載器 //如果文獻(xiàn)放在src目錄下,咱們應(yīng)當(dāng)使用類加載器來讀取(如果文獻(xiàn)在包下,還要寫上包途徑) InputStreamis=Servlet5.class.getClassLoader().getResourceAsStream("perties");獲取文獻(xiàn)全途徑 //如果讀取到一種文獻(xiàn)全途徑 Stringpath=this.getServletContext().getRealPath("/imgs/mao.jpg"); out.println("path="+path);ServletContext應(yīng)用在網(wǎng)站開發(fā)中,有諸多功能需要使用ServletContext,例如:網(wǎng)站計數(shù)器網(wǎng)站在線顧客顯示簡樸聊天系統(tǒng)...總之,如果是涉及到不同顧客共享數(shù)據(jù),而這些數(shù)據(jù)量不大,同步又不但愿寫入數(shù)據(jù)庫中,咱們就可以考慮使用ServletContext來實現(xiàn).//——————————————————————————————————————//——————————————————————————————————————//——————————————————————————————————————//——————————————————————————————————————問題:當(dāng)web服務(wù)器關(guān)閉后,咱們計數(shù)器就被清空了,請人們思考一下,如何可以保證計數(shù)器穩(wěn)定增長?當(dāng)服務(wù)器關(guān)閉時,ServletContext里信息要刷新到服務(wù)器端文獻(xiàn)中(數(shù)據(jù)庫也行)。重寫servletdestroy辦法。除此之外,還需要在web.xml中配備,load-on-startup,讓tomcat啟動后自動加載此servlet到內(nèi)存,這樣tomcat關(guān)閉時才會看到相應(yīng)信息。關(guān)閉服務(wù)器后控制臺顯示:*關(guān)閉應(yīng)當(dāng)用這種方式:或者這種方式為暴力關(guān)閉://——————————————————————————————————————代碼:咱們建立一種文獻(xiàn)record.txt文獻(xiàn),用于保存訪問量,可以保證穩(wěn)定增長。實現(xiàn)辦法:建立InitServlet,用于初始化我ServletContext,和在關(guān)閉tomcat時保存訪問量在counterWebRoot下創(chuàng)立一種text用于記錄服務(wù)器關(guān)閉時ServletContext信息:New->File//——————————————————————————————————————packagecom.wmc;importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.FileNotFoundException;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;importjava.io.PrintWriter;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;publicclassInitServletextendsHttpServlet{ /** *Destructionoftheservlet.<br> */ publicvoiddestroy(){ super.destroy();//Justputs"destroy"stringinlog //Putyourcodehere System.out.println("initservletdestroy()被調(diào)用.."); //把ServletContext值重新保存到文獻(xiàn). Stringfilepath=this.getServletContext().getRealPath("/record.text"); FileWriterfileWriter=null; BufferedWriterbufferedWriter=null; try{ fileWriter=newFileWriter(filepath); bufferedWriter=newBufferedWriter(fileWriter); Stringnums=(String)this.getServletContext().getAttribute("nums"); bufferedWriter.write(nums); }catch(IOExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); }finally{ //關(guān)閉 try{ bufferedWriter.close(); fileWriter.close(); }catch(IOExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } } publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriterout=response.getWriter(); } publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ th
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年甘肅會展中心有限責(zé)任公司招聘筆試參考題庫含答案解析
- 2025年全球及中國醫(yī)用協(xié)作機(jī)器人行業(yè)頭部企業(yè)市場占有率及排名調(diào)研報告
- 2025-2030全球鄰氯苯腈(氯化法)行業(yè)調(diào)研及趨勢分析報告
- 2025-2030全球觸控?zé)粜袠I(yè)調(diào)研及趨勢分析報告
- 遠(yuǎn)程教育中如何培養(yǎng)學(xué)生的自我約束力
- 運(yùn)動療法在醫(yī)療領(lǐng)域的新突破
- 教學(xué)創(chuàng)新與科研突破的相互關(guān)系研究
- 數(shù)據(jù)安全保衛(wèi)戰(zhàn)網(wǎng)絡(luò)安全教育專題研討與執(zhí)行總結(jié)
- 茶藝技能在商業(yè)領(lǐng)域的應(yīng)用與拓展
- 二零二五年度網(wǎng)絡(luò)安全技術(shù)支持與服務(wù)合同6篇
- 2024年全國職業(yè)院校技能大賽高職組(研學(xué)旅行賽項)考試題庫(含答案)
- 2025年溫州市城發(fā)集團(tuán)招聘筆試參考題庫含答案解析
- 2025年中小學(xué)春節(jié)安全教育主題班會課件
- 2025版高考物理復(fù)習(xí)知識清單
- 除數(shù)是兩位數(shù)的除法練習(xí)題(84道)
- 2025年度安全檢查計劃
- 2024年度工作總結(jié)與計劃標(biāo)準(zhǔn)版本(2篇)
- 全球半導(dǎo)體測試探針行業(yè)市場研究報告2024
- 反走私課件完整版本
- 2024年注冊計量師-一級注冊計量師考試近5年真題附答案
- 四年級下冊數(shù)學(xué)知識點(diǎn)總結(jié)
評論
0/150
提交評論