写了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");
%>
点击登录后的截图:
经过反复检查代码和查资料,感觉对数据的编码和解码的代码应该是没问题的,而且页面的编码都是"utf-8"格式的,后面仔细一想,是不是从request中读取出来的就已经是乱码了,然后在代码String userName=request.getParameter("userName");//获取用户名
的后面加上一句的测试的代码:System.out.println("userName="+userName);
然后测试,果然是这样的,截图如下:
知道了原因,就好解决了。在loginProcess.jsp页面中添加代码request.setCharacterEncoding("utf-8");就可以了。
再一次测试,输入时的截图:
点击登录后的截图:
控制台的截图:
好了,问题终于解决了,希望对需要的朋友有所帮助。