筆記如下
-
web.xml
4.png
-
用戶登錄
4.png 自動登錄過濾器
//自動登錄過濾器
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp= (HttpServletResponse) response;
//判斷是否已經登錄
//如果登錄,信息存在session中
if( req.getSession().getAttribute("loginUser") != null ){
//說明已經登錄,直接放行
chain.doFilter(req, resp);
}else{
//說明沒有登錄
//找目標cookie
Cookie[] cookies = req.getCookies();
Cookie targetCookie = findTargetCookie(cookies,"autologn");
if (targetCookie == null) {
//沒找到目標cookei
chain.doFilter(req, resp);
}else{
//找到了,
String username = targetCookie.getValue().split("#")[0];
String password = targetCookie.getValue().split("#")[1];
//去登陸,去數據庫查找用戶信息
UserService us =new UserService();
User loginUser = us.loginByUsernameAndPassword(username,password);
if (loginUser == null) {
//說明用戶名和密碼被篡改了
//放行
chain.doFilter(req, resp);
}else{
//將user存到session中去
req.getSession().setAttribute("loginUser", loginUser);
chain.doFilter(req, resp);
}
}
}