Solve Tomcat use cookie Chinese garbled problem, javaweb novice
1 Public classCookieTestextendsHttpServlet {2 3 4 Public voiddoget (httpservletrequest request, httpservletresponse response)5 throwsservletexception, IOException {6 7String currentdate =mcurrentdate ();8String date =NULL;9 Tencookie[] Cookies =getcookies (request); One A if(Cookies = =NULL){ -Date = "Welcome to the station, current time:" +currentdate; -}Else { the for(Cookie cookie:cookies) { - //decode Urldecoder.decode (Cookies[i].getname (), "Utf-8") -System.out.println (Urldecoder.decode (Cookie.getname (), "Utf-8") -+ "=" + (Urldecoder.decode (Cookie.getvalue (), "Utf-8")))); + - if("Lasttime". Equals (Urldecoder.decode (Cookie.getname (), "Utf-8"))){ +Date = "Last access time:" + Urldecoder.decode (Cookie.getvalue (), "Utf-8"); A}Else { atDate = "Welcome to the station, current time:" +currentdate; - } - } - - //coded Urlencoder.encode (currentdate, "Utf-8"); -Setcookie (Urlencoder.encode (currentdate, "Utf-8"), response); in } - toResponse.setcontenttype ("Text/html;charset=utf-8"); +Response.getoutputstream (). Write (Date.getbytes ("Utf-8")); - the } * $ /**Panax Notoginseng * Get current time - * @return the */ + PublicString mcurrentdate () { ADate Date =NewDate (); theSimpleDateFormat DateFormat =NewSimpleDateFormat ("yyyy mm month DD Day HH:MM:SS"); + returnDateformat.format (date); - } $ $ /** - * Set Cookies - * @paramcurrentdate Current Time the * @paramResponse HttpServletResponse - */Wuyi Public voidSetcookie (String currentdate,httpservletresponse response) { theCookie cookie =NewCookie ("Lasttime",NULL); -Cookie.setmaxage (60*60*24*30); Wu Cookie.setvalue (currentdate); - Response.addcookie (cookie); About } $ - /** - * Get Cookies - * @paramRequest HttpServletRequest A * @returnCookie Collection + */ the Publiccookie[] GetCookies (HttpServletRequest request) { - returnrequest.getcookies (); $ } the}
Use a cookie from a servlet to get a user's last access time