解决tomcat使用Cookie中文乱码问题,javaWeb新手
1 public class CookieTest extends HttpServlet { 2 3 4 public void doGet(HttpServletRequest request, HttpServletResponse response) 5 throws ServletException, IOException { 6 7 String currentDate = mCurrentDate(); 8 String date = null; 9 10 Cookie[] cookies = getCookies(request); 11 12 if(cookies == null){ 13 date = "欢迎访问小站,当前时间:" + currentDate; 14 } else { 15 for (Cookie cookie : cookies) { 16 //解码URLDecoder.decode(cookies[i].getName(),"utf-8") 17 System.out.println(URLDecoder.decode(cookie.getName(),"utf-8") 18 + "=" + (URLDecoder.decode(cookie.getValue(),"utf-8"))); 19 20 if("LastTime".equals(URLDecoder.decode(cookie.getName(),"utf-8"))){ 21 date = "上次访问时间:" + URLDecoder.decode(cookie.getValue(),"utf-8"); 22 } else { 23 date = "欢迎访问小站,当前时间:" + currentDate; 24 } 25 } 26 27 //编码URLEncoder.encode(currentDate, "utf-8"); 28 setCookie(URLEncoder.encode(currentDate, "utf-8"), response); 29 } 30 31 response.setContentType("text/html;charset=utf-8"); 32 response.getOutputStream().write(date.getBytes("utf-8")); 33 34 } 35 36 /** 37 * 获取当前时间 38 * @return 39 */ 40 public String mCurrentDate(){ 41 Date date = new Date(); 42 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); 43 return dateFormat.format(date); 44 } 45 46 /** 47 * 设置cookie 48 * @param currentDate 当前时间 49 * @param response HttpServletResponse 50 */ 51 public void setCookie(String currentDate,HttpServletResponse response){ 52 Cookie cookie = new Cookie("LastTime", null); 53 cookie.setMaxAge(60*60*24*30); 54 cookie.setValue(currentDate); 55 response.addCookie(cookie); 56 } 57 58 /** 59 * 获取cookie 60 * @param request HttpServletRequest 61 * @return Cookie集合 62 */ 63 public Cookie[] getCookies(HttpServletRequest request){ 64 return request.getCookies(); 65 } 66 }
时间: 2024-10-11 16:52:20