关于Cookie的中文问题
如果出现Cookie不能保存中文字符问题,可以导入Java.net.*包
使用其中的URLEncoder.encode()方法编码和URLDecoder.decode()方法解码
示例如下:
<%@ page language="java" import="java.util.*,java.net.*" contentType="text/html; charset=utf-8"%> <% request.setCharacterEncoding("utf-8"); String username=""; String password=""; Cookie[] cookies=request.getCookies(); if(cookies!=null&&cookies.length>0){ for(Cookie c:cookies){ if(c.getName().equals("username")||c.getName().equals("password")){ username=URLDecoder.decode(c.getValue(),"utf-8"); } if(c.getName().equals("password")){ password=URLDecoder.decode(c.getValue(),"utf-8"); } } } %>
<%@ page language="java" import="java.util.*,java.net.*" contentType="text/html; charset=utf-8"%> <% String [] isUseCookies=request.getParameterValues("isUseCookie"); if(isUseCookies!=null&&isUseCookies.length>0){ String username=URLEncoder.encode(request.getParameter("username"),"utf-8"); String password =URLEncoder.encode(request.getParameter("password"),"utf-8"); Cookie usernameCookie=new Cookie("username",username); Cookie passwordCookie = new Cookie("password",password); usernameCookie.setMaxAge(864000); passwordCookie.setMaxAge(864000); response.addCookie(usernameCookie); response.addCookie(passwordCookie); }else{ Cookie[] cookies=request.getCookies(); if(cookies!=null&&cookies.length>0){ for(Cookie c:cookies){ if(c.getName().equals("username")||c.getName().equals("password")){ c.setMaxAge(0); response.addCookie(c); } } } } %>