账户Cookie还是乱码 å¼ ä
<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
import="java.util.*,java.net.*" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<% String username="";
String password="";
request.setCharacterEncoding("utf-8");
Cookie[] cookies = request.getCookies();
if(cookies!=null&&cookies.length>0){
for(Cookie cookie:cookies){
if(cookie.getName().equals("username")){
username=URLDecoder.decode(cookie.getValue(), "utf-8");
}
if(cookie.getName().equals("password")){
password=URLDecoder.decode(cookie.getValue(),"utf-8");
}
}
}
%>
<title>登录界面</title>
</head>
<body>
<form name="regForm" action="dologin.jsp" method="post">
<table>
<tr><td>用户名:</td><td><input type="text" name="username" value="<%=username %>"></td></tr>
<tr><td>密码</td><td><input type="password" name="password" value="<%=password %>"></td></tr>
<tr><td colspan="2"><input type="checkbox" name="isUseCookie" checked="checked" />是否保存登录信息</td></tr>
<tr><td colspan="2"><input type="submit" value="登录" class="login"/><input type="reset" value="取消"/></td></tr>
</table>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=utf-8"
import="java.net.*" pageEncoding="utf-8"%>
<jsp:useBean id="loginUser" class="com.po.Users" scope="page"></jsp:useBean>
<jsp:useBean id="userDao" class="com.dao.UsersDao" scope="page"></jsp:useBean>
<jsp:setProperty property="*" name="loginUser"/>
<%
String path=request.getContextPath();
String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getRemoteAddr();
request.setCharacterEncoding("utf-8"); //防止中文乱码
//首先判断用户是否选择记住了登录状态
String[] isUseCookies =request.getParameterValues("isUseCookie");
if(isUseCookies!=null&&isUseCookies.length>0){
//把用户名和密码保存在Cookies里面
String userName= URLEncoder.encode(request.getParameter("username"),"utf-8");
//使用URLEncoder解决无法在Cookie当中保存中文字符串问题
String passWord= URLEncoder.encode(request.getParameter("password"),"utf-8");
Cookie usernameCookie=new Cookie("username",userName);
Cookie passwordCookie=new Cookie("password",passWord);
usernameCookie.setMaxAge(864000);//设置Cookie最大生存期限为1天
passwordCookie.setMaxAge(864000);
response.addCookie(usernameCookie);
response.addCookie(passwordCookie);
}
else{
Cookie[] cookies = request.getCookies();
if(cookies!=null&&cookies.length>0){
for(Cookie cookie:cookies){
if(cookie.getName().equals("username")||cookie.getName().equals("password")){
cookie.setMaxAge(0); //设置Cookie失效
response.addCookie(cookie); //重新保存。
}
}
}
}
//如果用户名和密码都等于admin,则跳转至,否则,返回原页面
if(userDao.usersLogin(loginUser)){
session.setAttribute("loginUser", loginUser.getUsername());
request.getRequestDispatcher("login_success.jsp").forward(request, response);
}
else
{
response.sendRedirect("login_failure.jsp");
}
%>