您的位置:首页 > 其它

手机网上商城-项目经验总结(十)-自动登录

2017-10-07 20:50 501 查看
10.自动登录功能

//登录
public void login(HttpServletRequest request,
HttpServletResponse response) throws IOException, IllegalAccessException, InvocationTargetException, ServletException{
Map<String,String[]> map = request.getParameterMap();
User user = new User();
BeanUtils.populate(user,map);
if (map.get("autoLogin")!=null){
Cookie username = new Cookie("username", map.get("username")[0]);
username.setMaxAge(60*60);
Cookie password = new Cookie("password", map.get("password")[0]);
password.setMaxAge(60*60);
response.addCookie(username);
response.addCookie(password);
}
user = us.login(user);
if (user != null){
request.getSession().setAttribute("user", user);
response.sendRedirect("/ShopStore/default.jsp");
}
else{
request.setAttribute("message", "用户或密码错误!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
//登出
public void logout(HttpServletRequest request,
HttpServletResponse response) throws IOException, IllegalAccessException, InvocationTargetException, ServletException
{
Cookie[] cookies = request.getCookies();
if (cookies != null){
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username") || cookie.getName().equals("password")){
//删除cookie
cookie.setMaxAge(0);
response.addCookie(cookie);//必须,否则实现不了
}
}
}
request.getSession().removeAttribute("user");
response.sendRedirect("/ShopStore/");
}
}
自动登录采用cookie的方式,并且设有有效时间。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: