您好,欢迎访问三七文档
©2011MartyHallHdliCkiHandlingCookiesOriginalsofSlidesandSourceCodeforExamples::©2011MartyHallForliveJavaEEtraining,pleaseseetrainingcoursesat://courses.coreservlets.com/.Servlets,JSP,JSF2,Ajax(withjQuery,Dojo,Prototype,Ext-JS,etc.),GWT,Java6,SOAP-basedandRESTfulWebServices,Spring,Hibernate/JPAAndroidandcustomizedcombinationsoftopicsHibernate/JPA,Android,andcustomizedcombinationsoftopics.TaughtbytheauthorofCoreServletsandJSP,MoreServletsandJSPandthistutorialAvailableatpublicCustomizedJavaEETraining:@coreservlets.comfordetails.Agenda•Understandingthebenefitsanddrawbacksfkiofcookies•SendingoutgoingcookiesRiiiiki•Receivingincomingcookies•TrackingrepeatvisitorsSifikittibt•Specifyingcookieattributes•Differentiatingbetweensessioncookiesandpersistentcookiespersistentcookies•Simplifyingcookieusagewithutilityclasses•Modifyingcookievalues•Modifyingcookievalues•Rememberinguserpreferences4ThePotentialofCookies•Idea–Servletsendsasimplenameandvaluetoclient.–Clientreturnssamenameandvaluewhenitconnectstosamesite(orsamedomaindependingoncookiesamesite(orsamedomain,dependingoncookiesettings).•TypicalUsesofCookiesyp–Identifyingauserduringane-commercesession•Servletshaveahigher-levelAPIforthistask.Ingeneral,session-tracking(nextlecture)isbetterforshort-termsessiontracking(nextlecture)isbetterforshorttermtrackingofuserinformation.–AvoidingusernameandpasswordCtiiit–Customizingasite–Focusingadvertising5CookiesandFocusedAdvertisingAdvertisingAmazon.comhomepageforrepeatvisitor.Booksshownarebasedonpriorhistory.6Amazon.comhomepagefornewvisitororvisitorwithcookiesdisabled.CookiesandPrivacyFoxTrot©1998BillAmendReprintedwithpermissionofFoxTrot©1998BillAmend.ReprintedwithpermissionofUniversalPressSyndicate.Allrightsreserved.7SomeProblemswithCookies•Theproblemisprivacy,notsecurity.–Serverscanrememberyourpreviousactions–Ifyougiveoutpersonalinformation,serverscanlinkthatinformationtoyourpreviousactionsinformationtoyourpreviousactions–Serverscansharecookieinformationthroughuseofacooperatingthirdpartylikedoubleclick.net–Poorlydesignedsitesstoresensitiveinformationlikecreditcardnumbersdirectlyincookie–JavaScriptbugslethostilesitesstealcookies(oldbrowsers)–JavaScriptbugslethostilesitesstealcookies(oldbrowsers)•Moralforservletauthors–Ifcookiesarenotcriticaltoyourtask,avoidservletsthatcooesaeotctcatoyoutas,avodsevetstattotallyfailwhencookiesaredisabled–Don’tputsensitiveinfoincookies8ManuallyDeletingCookies(ToSimplifyTesting)(ToSimplifyTesting)9SendingCookiestotheClient•CreateaCookieobject.–CalltheCookieconstructorwithacookienameandacookievalue,bothofwhicharestrings.Cookiec=newCookie(userIDa1234);Cookiec=newCookie(userID,a1234);•Setthemaximumage.–Totellbrowsertostorecookieondiskinsteadofjustin–Totellbrowsertostorecookieondiskinsteadofjustinmemory,usesetMaxAge(argumentisinseconds)c.setMaxAge(60*60*24*7);//Oneweek•PlacetheCookieintotheHTTPresponse–Useresponse.addCookie.–Ifyouforgetthisstep,nocookieissenttothebrowser!response.addCookie(c);10ReadingCookiesfromtheClient•Callrequest.getCookiesThisyieldsanarrayofCookieobjects–ThisyieldsanarrayofCookieobjects.•Loopdownthearray,callinggetNameoneachentryuntilyoufindthecookieofinterest–Usethevalue(getValue)inapplication-specificway.StringcookieName=userID;StringcookieName=userID;Cookie[]cookies=request.getCookies();if(cookies!=null){()for(Cookiecookie:cookies){if(cookieName.equals(cookie.getName())){doSomethingWith(cookie.getValue());}}}11UsingCookiestoDetectFirst-TimeVisitorsFirst-TimeVisitors@WebServlet(/repeat-visitor)publicclassRepeatVisitorextendsHttpServlet{publicclassRepeatVisitorextendsHttpServlet{publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletExceptionIOException{throwsServletException,IOException{booleannewbie=true;Cookie[]cookies=request.getCookies();if(ki!ll){if(cookies!=null){for(Cookiec:cookies){if((c.getName().equals(repeatVisitor))&&(()()))(c.getValue().equals(yes))){newbie=false;break;}}}12UsingCookiestoDetectFirst-TimeVisitors(Continued)First-TimeVisitors(Continued)Stringtitle;if(newbie){if(newbie){CookiereturnVisitorCookie=newCookie(repeatVisitor,yes);returnVisitorCookiesetMaxAge(60*60*24*365);returnVisitorCookie.setMaxAge(60*60*24*365);response.addCookie(returnVisitorCookie);title=WelcomeAboard;}l{}else{title=WelcomeBack;}(/)response.setContentType(text/html);PrintWriterout=response.getWriter();…//(Outputpagewithabov
本文标题:Beginning & Intermediate Servlet & JSP Tutorials-0
链接地址:https://www.777doc.com/doc-5536530 .html