我用的服务器是tomcat7,可能7对中文的支持不是很好。
我想要把用户名(中文)存到cookie中,以后打开时再读取。
- Java code
response.setContentType("text/html"); PrintWriter out = response.getWriter(); request.setCharacterEncoding("UTF-8"); String uname = request.getParameter("username"); String upwd = request.getParameter("password"); String remember = request.getParameter("remember"); Userinfo u = new Userinfo(); u.setUsermail(uname); u.setPassword(upwd); UserinfoBiz ub = new UserinfoBizImpl(); if (ub.login(u)) { if (remember != null) { uname=new String(uname.getBytes("iso8859-1")); Cookie ckuname = new Cookie("uname", uname); Cookie ckupwd = new Cookie("upwd", upwd); ckuname.setMaxAge(60 * 60 * 24 * 365); ckupwd.setMaxAge(60 * 60 * 24 * 365); response.addCookie(ckuname); response.addCookie(ckupwd); } request.getSession().setAttribute("username", uname); request.getSession().setAttribute("password", upwd); response.sendRedirect("myindex"); } else { response.sendRedirect("login"); } out.close();
因为中文没法写入,所以我在写入之前把编码转成了iso8859-1.
现在我应该在读取的servlet中转成utf-8。。
为什么我转不回来了。。。代码如下。。
- Java code
if (cookie[i].getName().equals("uname")) { unameString = cookie[i].getValue(); unameString=new String(unameString.getBytes("iso8859-1"),"utf-8"); }
悲剧啊。求解决。。。
------解决方案--------------------------------------------------------
用encodeURI进行传递参数。