Filter自动登录
Dao层略过
Domain略过
Service层过
Web层
Select逻辑
获取表单数据,Web—service——Dao返回用户信息
如果返回不为null否则,重定向到登录页面。则判断用户是否勾选7天免登录,如果勾选(判断一下)。把用户数据存入session域中,并且要创建一个cookie设置时间为7天,保存cookie中.
select代码:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获得表单数据 String name = request.getParameter("username"); String password = request.getParameter("password"); //查询有没有该用户 User u = new User(name, password); UserService us = new UserServiceImpl(); User user = us.login(u); //用户账号密码正确 if (user != null) { //判断是否勾选7天免登陆 if ("ok".equals(request.getParameter("auto"))) { //数据保存到session中 request.getSession().setAttribute("user", user); //保存信息到cookie中 Cookie cookie = new Cookie("auto#"+name, password); cookie.setMaxAge(70 * 60); cookie.setPath("/"); response.addCookie(cookie); } request.getRequestDispatcher("main.jsp").forward(request, response); } else { response.sendRedirect("/autoFiler/index.jsp"); } }
Filter过滤器逻辑
Filter主要过滤index.jsp
获得cookie数组进行非空判断,如果cookie有值则遍历之,判断cookie是否是保存的有username的值,如果有则进行把cookie保存的用户名密码取出,调用service——Dao判断用户是否存在,如果存在转发到mian.jsp,并放行。如果不存在,重定向到index.Jsp登录页面。如果cookie数组中没有保存该用户的cookie,则放行。
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; //1. 获取cookie 判断非空 Cookie[] cookies = req.getCookies(); if(cookies!=null){ //2. 遍历cookie for (Cookie cookie : cookies) { //3. 判断cookie存在 name命名的值 if(cookie.getName().contains("auto")){ String username=cookie.getName().split("#")[1]; String password=cookie.getValue(); User u=new User(username,password); UserService us = new UserServiceImpl(); User user = us.login(u); //4.如果user对象存在 自动登录 if(user!=null){ req.getSession().setAttribute("user", user); request.getRequestDispatcher("main.jsp").forward(request, response); chain.doFilter(req, res); }else{ //5.如果不存在,重新跳转至登录页面 res.sendRedirect("/autoFiler/index.jsp"); chain.doFilter(req, res); } } } chain.doFilter(req, res); } }