Cookie中文乱码问题
页面一登录,页面二保存用户信息,放入Cookies里。
但是Cookies放入中文会引起编码问题,如报错“Control character in cookie value, consider BASE64 encoding your value”等,
利用decode和encode处理编码可以解决此问题。
页面一 index.jsp
<body> 请填写您的身份标识 <form action="bl.jsp"> 用户名: <input type="text" name="name" style="width: 200px"> <br /> 密 码 : <input type="password" name="pwd" style="width: 200px"> <br /> <input type="submit" value="访问" name="sub" /> <% //读取cookies Cookie[] cookies = request.getCookies(); String uname = ""; if (cookies == null) { out.print("您还没有登录!"); } else { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("uname")) { uname = cookies[i].getValue(); uname = java.net.URLDecoder.decode(uname, "UTF-8");//解码 //也可以在顶部@page import="java.net.URLEncoder" out.print("用户标识为" + uname); } } } %> </form> </body>
页面二 bl.jsp
<body> <% String name=request.getParameter("name");//取表单上的用户名 name=new String(name.getBytes("iso8859-1"),"utf-8");//已转化为中文 name=URLEncoder.encode(name,"UTF-8");//encode将编码转化为通用码 Cookie cookie = null; cookie = new Cookie("uname", name);//放入cookies cookie.setMaxAge( 24 * 60 * 60);//一天 response.addCookie(cookie); //放入 response.sendRedirect("index.jsp"); %> </body>
![赞赏:https://images2018.cnblogs.com/blog/1023587/201802/1023587-20180226133036435-1544066188.png](https://images2018.cnblogs.com/blog/1023587/201802/1023587-20180226133036435-1544066188.png)