过滤器实现自动登录

过滤器实现自动登录


概要

1,什么是一次会话?
2,什么是自动登录?
3,如何实现该需求?
4,代码实现



1,什么是一次会话?
是从客户从打开浏览器浏览某个网站,发送请求开始,到关闭浏览器这整个过程称为和该站点服务器的一次会话;
这期间客户可以打开多个网页,如打开某宝,搜索几件物品,没找到合适的,然后再去某东上,这时虽然已经关闭某宝的网页,但是浏览器把客户和该服务器的会话数据存储在浏览器本地内存中,会话没有结束,当客户把浏览器关闭后,这次会话才算真正结束!
2,什么是自动登录?
在客户在对某个网站进行登录时,下面有个选框–自动登录,如果客户选上该选框,则发送请求到服务器时,服务器要做出相应处理,而在客户关闭浏览器,会话结束后,在一定时间范围内再打开网页访问该网站,不直接进行登录,而在该网站登录还是有效的.
3 如何实现该需求?
1),首先后台服务器先对客户端请求做判断,是否有选中自动登录需求
2),如是,再对登录验证成功后,创建Cookie,保存该用户登录信息,并对该Cookie做一定时间的持久化操作(即设置该Cookie保存在客户端本地硬盘时间,默认是保存在浏览器内存中,浏览器关闭,则该cookie不再了),将Cookie响应回客户端.
3),借助过滤器 —过滤器对客户端发送的请求,首先获取客户端发送的Cookie,做判空处理(第一次请求很可能没cookie),若有,遍历Cookie数组,判断是否有用户的登录信息,若有,获取保存到session域中.
4,实现代码


验证用户登录的代码 –Servlet部分

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

  public class CheckLoginServlet extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response) 
                throws ServletException ,IOException {
            //1,获取用户用户名和密码值
            String username = request.getParameter("username");
            String password = request.getParameter("password");
             //判断用户是否要选择自动登录,表单中提供该选框
            String autoLogin=request.getParameter("autoLogin");
              //创建session域对象
            HttpSession session = request.getSession();

            //2 数据库验证--简单验证
             if(username !=null && password !=null ) {

             数据库验证....此处省略  返回user对象

            if(user!=null) { //有该对象,则登录成功

            //验证成功
            session.setAttribute("user",user);//其他页面可能会用到该user对象的数据

                 if("autoLogin".equals(autoLogin)){
         //要求自动登录,需将用户信息放到cookie中,发送回客户端

           //因cookie中不能有中文,如果用户名有中文,需编码处理
                                    //URLEncoder类要java.net包下类       
                            username=URLEncoder.encode(username, "utf-8");

                        Cookie  username_cookie=new Cookie("username",username);
                        Cookie  password_cookie=new Cookie("password",password);

                        //设置cookie的持久化时间
                        username_cookie.setMaxAge(60*60*2); //cookie 保留2小时,仅为试验,cookie过期则被清空
                        password_cookie.setMaxAge(60*60*2);

                        //设置cookie的携带路径,当前项目的所有资源
                        username_cookie.setPath(request.getContextPath());
                        password_cookie.setPath(request.getContextPath());
//发送cookie回客户端,将该cookie保存到客户端本地硬盘(考虑的是客户端没有禁用cookie的情况哈)
                        response.addCookie(password_cookie);
                        response.addCookie(username_cookie);
                    }
                      //等同于request.getContextPath(),获取当前项目名
      response.sendRedirect(request.getServletContext().getContextPath()+"/main.jsp");
                }
                else{
                    //验证失败
                    request.setAttribute("userInfo", "用户名或密码有误!");
              //返回登录页面
            request.getRequestDispatcher("/index.jsp").forward(request, response);
                }
             }
        }
      }

过滤器代码实现 –此处只放 doFilter方法代码部分


public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

          //进行类型强转
         HttpServletRequest  req=(HttpServletRequest) request;
         HttpServletResponse res=(HttpServletResponse) response;
         //获取session域对象
         HttpSession session = req.getSession();
         String username=null;
         String  password=null;
         User  user=null;

        //1,从cookie中获取数据,cookie中是以键值对存在的
        Cookie[] cookies=req.getCookies(); 
        if(cookies!=null) { 
                for (Cookie cookie : cookies) {
                    //只获取key为 username和password的cookie
                    if("username".equals(cookie.getName())){
                       // 获取该cookie的值
                      username=cookie.getValue(); 

                    //解码,在上面的Servlet中把获取编码了,此处要还原
                     username= URLDecoder.decode(username, "utf-8");
                    }
                    if("password".equals(cookie.getName())) {
                        password=cookie.getValue();
                    }
                }
       }

        if(username!=null && password != null) {

           //自己写的进行数据库验证的方法,大家可忽视,只是进行数据库验证的方法...
            UserService userService=new UserService();
            user=userService.login(username, password);
            //3,将user放入到session域中,不论user是否存在,如果为空,也不影响
            session.setAttribute("user",user);
            //重点: 放到该域中,在访问该网站其他资源时,session中都有该user对象,即可实现免登录的操作.
        } 

        //4放行
        chain.doFilter(req, res);
    }

解决请求和响应的中文乱码问题,可单独放在一个过滤器中,配置过滤web应用下的所有资源


public void doFilter(ServletRequest request, ServletResponse response, FilterChain   chain) 
 throws IOException, ServletException {
         //解决请求和响应的中文乱码问题
         request.setCharacterEncoding("utf-8");
         response.setContentType("text/html;charset=utf-8");
        //放行
        chain.doFilter(request, response);
    }



水平有限,如有错误,敬请指点,感激不尽!

猜你喜欢

转载自blog.csdn.net/qq_39494996/article/details/81637049
今日推荐