import cn.itcast.service.UserService;
importcn.itcast.service.impl.UserServiceImpl;
publicclass AutologinFilter implements Filter{
@Override
publicvoid destroy() {
}
@Override
publicvoid doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//第一步: 获取数据 (cookie username password)
//HttpServletRequest?
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
Cookie[] cookies = req.getCookies();
if(cookies == null){
res.sendRedirect(req.getContextPath()+"/login.jsp");
return;
}else{
//将cookie中的username和password
String username = "";
String password = "";
for (Cookie cookie : cookies) {
if("username".equals(cookie.getName())){
username = URLDecoder.decode(cookie.getValue(), "utf-8") ;
}
if("password".equals(cookie.getName())){
password = cookie.getValue();
}
}
if(username.equals("") || password.equals("")){
res.sendRedirect(req.getContextPath()+"/login.jsp");
return;
}else{
//第二步:调用方法(UserService.login())
UserService userService = newUserServiceImpl();
User loginUser = userService.login(username, password);
//第三步:根局不同返回值,不同处理
if(loginUser == null){
res.sendRedirect(req.getContextPath()+"/login.jsp");
return;
}else{
req.getSession().setAttribute("loginUser", loginUser);
res.sendRedirect(req.getContextPath()+"/queryPage2?pageNum=1");
return;
}
}
}
}
@Override
publicvoid init(FilterConfig arg0) throws ServletException {
}
}
web.xml配置:
<!-- =======================过滤器配置=============================== -->
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/shouji/article-47577-6.html
必须小心~