cookie中存储中文的处理问题


      工具:eclipse  tomcat7.0

   写了2个jsp页面,登录界面是userLogin.jsp,登录的处理界面是loginProcess.jsp.

1.userLogin.jsp的代码:

<body>
<%
String userName=null;
String password=null;
String userInfo=null;
Cookie[] cookies=request.getCookies();
for(int i=0;cookies!=null && i<cookies.length;i++){
if(cookies[i].getName().equals("userNameAndpassword")){
String value=cookies[i].getValue();
userInfo=URLDecoder.decode(value,"utf-8");
userName=userInfo.split("_")[0];
password=userInfo.split("_")[1];
}
}

if(userName==null){
userName="";
}
if(password==null){
password="";
}
%>
<form action="loginProcess.jsp" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" id="userName" name="userName" value="<%=userName %>"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" id="password" name="password" value="<%=password %>"/></td>
</tr>
<tr>
<td>记住密码:</td>
<td><input type="checkbox" id="remember" name="remember" value="remember-me"/></td>
</tr>
<tr>
<td><input type="submit" value="登录"/></td>
<td><input type="button" value="重置" οnclick="resetValue()"/></td>
</tr>
</table>
</form>
</body>


2.loginProcess.jsp页面的代码:

<%
String userName=request.getParameter("userName");//获取用户名
String password=request.getParameter("password");//获取密码
String remember=request.getParameter("remember");//获取是否记住密码
if("remember-me".equals(remember)){
String value=userName+"_"+password;
Cookie userNameAndpassword=new Cookie("userNameAndpassword",URLEncoder.encode(value,"utf-8"));
userNameAndpassword.setMaxAge(1*60);// cookie记录60miao 
response.addCookie(userNameAndpassword);
System.out.println("设置Cookie成功");
}
System.out.println("登录成功");
response.sendRedirect("userLogin.jsp");
%>



3.测试。
在浏览器中输入地址测试发现,总是乱码。输入时的截图:


点击登录后的截图:


经过反复检查代码和查资料,感觉对数据的编码和解码的代码应该是没问题的,而且页面的编码都是"utf-8"格式的,后面仔细一想,是不是从request中读取出来的就已经是乱码了,然后在代码String userName=request.getParameter("userName");//获取用户名

的后面加上一句的测试的代码:System.out.println("userName="+userName);

然后测试,果然是这样的,截图如下:




知道了原因,就好解决了。在loginProcess.jsp页面中添加代码request.setCharacterEncoding("utf-8");就可以了。

再一次测试,输入时的截图:


点击登录后的截图:


控制台的截图:


好了,问题终于解决了,希望对需要的朋友有所帮助。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值