登录过滤器

当用户访问某个网站的信息时,我们希望用户在已经登录的情况下才能继续访问本网站或者是用户在浏览器上已经有了相应的cookie也可以就行访问网站,这时候我们就需要一个登录过滤器来过滤掉对网站内其他页面的请求。

一、编写LoginFilter类

该类必须继承Filter接口,Filter接口在javax.servlet包中,以下是该接口的内容:

public interface Filter {
    void init(FilterConfig var1) throws ServletException;

    void doFilter(ServletRequest var1, ServletResponse var2, FilterChain var3) throws IOException, ServletException;

    void destroy();
}

可以看到该接口有三个方法,init方法是在过滤初始化时执行,doFilter方法主要是过滤器所执行的具体内容,destroy方法在过滤器结束时执行。
下面是我编写的LoginFilter方法:

public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    String initParam = filterConfig.getInitParameter("ref");
    System.out.println("过滤器初始化参数:"+initParam);
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    //        获得request,response,session对象
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    HttpSession session = req.getSession();
    String contextPath = req.getContextPath();
    //        获得用户请求的uri(相对地址)
    String path = req.getRequestURI();
    //        获取session中作为判断的字段
    String pwd = (String) session.getAttribute("pw");
    //        判断请求中是否包含了登录页面的请求 不过滤登录页面
    //indexOf(String str) 返回该子字符串str在该字符串中第一次出现处的索引,若没有该字符则返回-1
    if(path.indexOf("/signin.jsp" ) > -1){
        filterChain.doFilter(req,resp);
    }
    else {
        //如果为其他页面 那么就要判断session中是否有标志
        if(pwd ==null || "".equals(pwd)){
            resp.sendRedirect(contextPath+"/signin.jsp");
        }
        else {
            filterChain.doFilter(req,resp);
        }
    }
}

@Override
public void destroy() {

    }
}

二、指定过滤的路径

配置web.xml文件


    loginFilter
    com.util.LoginFilter


    loginFilter
    *.jsp


    loginFilter
    *.html

你可能感兴趣的:(登录过滤器)