javaWeb的session和cookie实现记住密码自动登录功能简单实例

关键代码:

jsp:


${msg}
用户名
密码

记住密码

servlet:

Map map = request.getParameterMap();
User user=new User();
BeanUtils.populate(user, map);

UserService us=new UserService();
User uu = us.logu(user);
if(uu !=null){
String auto_login = request.getParameter("auto_login");
if("true".equals(auto_login)){
Cookie cookie=new Cookie("auto_login", uu.getUsername()+"#"+uu.getPassword());
cookie.setPath(this.getServletContext().getContextPath());
cookie.setMaxAge(60*60*24*7);
response.addCookie(cookie);
}
request.getSession().setAttribute("exitUser", uu);
response.sendRedirect(this.getServletContext().getContextPath()+"/demo04login/show.jsp");

}else{
request.setCharacterEncoding("utf-8");
request.getSession().setAttribute("msg", "登录失败");
request.getRequestDispatcher("/demo04login/login.jsp").forward(request, response);
}
Filter:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest) request;
HttpSession session = req.getSession();
Object exitUser = session.getAttribute("exitUser");
//判断session中用户是否存在
if(exitUser!=null){
chain.doFilter(request, response);

}else{
//判断cookie是否存在

Cookie[] cookies = req.getCookies();
Cookie findCookie = CookieUtils.findCookie(cookies, "auto_login");
if(findCookie==null){

chain.doFilter(request, response);
}else{

//查找数据库匹配账号密码
String auto_login = findCookie.getValue();
String[] split = auto_login.split("#");
User user=new User();
user.setUsername(split[0]);
user.setPassword(split[1]);
UserService us=new UserService();
try {
User uu = us.logu(user);
if(uu==null){

chain.doFilter(request, response);
}else{

session.setAttribute("exitUser", uu);
chain.doFilter(request, response);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}
--------------------- 
作者:西瓜菠萝 
来源:CSDN 
原文:https://blog.csdn.net/dll_2016/article/details/72860987 
版权声明:本文为博主原创文章,转载请附上博文链接!

你可能感兴趣的:(开发)