Javaweb实现登录界面“记住我”功能

1.在后台上写cookie

private void rememberMe(String userName, String password, String userType, HttpServletResponse response) {
Cookie user = new Cookie("dormuser", userName+"-"+password+"-"+userType+"-"+"yes");
user.setMaxAge(1*60*60*24*7);
response.addCookie(user);
}

private void deleteCookie(String userName, HttpServletRequest request, HttpServletResponse response) {
Cookie[] cookies=request.getCookies();
for(int i=0;cookies!=null && i if(cookies[i].getName().equals("dormuser")){
if(userName.equals(userName=cookies[i].getValue().split("-")[0])) {
Cookie cookie = new Cookie(cookies[i].getName(), null);
cookie.setMaxAge(0);
response.addCookie(cookie);
break;
}
}
}
}

2.前台上获取cookie


<%
if(request.getAttribute("user")==null){
String userName=null;
String password=null;
String userType=null;
String remember=null;

Cookie[] cookies=request.getCookies();
for(int i=0;cookies!=null && i if(cookies[i].getName().equals("dormuser")){
userName=cookies[i].getValue().split("-")[0];
password=cookies[i].getValue().split("-")[1];
userType=cookies[i].getValue().split("-")[2];
remember=cookies[i].getValue().split("-")[3];
}
}

if(userName==null){
userName="";
}

if(password==null){
password="";
}

if(userType==null){
userType="";
} else if("admin".equals(userType)){
pageContext.setAttribute("user", new Admin(userName,password));
pageContext.setAttribute("userType", 1);
} else if("dormManager".equals(userType)) {
pageContext.setAttribute("user", new DormManager(userName,password));
pageContext.setAttribute("userType", 2);
} else if("student".equals(userType)) {
pageContext.setAttribute("user", new Student(userName,password));
pageContext.setAttribute("userType", 3);
}

if("yes".equals(remember)) {
pageContext.setAttribute("remember", 1);
}

}
%>


3.输入框中设置默认值


你可能感兴趣的:(Javaweb)