spring下登录过滤器的实现

首先定义一个类继承Filter类
/**

  • 登录过滤器
  • 注意:使用不包括(css、js、png、bmp)为后缀的文件时可能需要在doFilter()方法中进行配置,防止文件被过滤器过滤掉
  • @author yeming
    */

public class LoginFilter implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {

}

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    //获取应用根目录
    String basePath = request.getScheme()+"://"
                      +request.getServerName()+":"+request.getServerPort()+request.getContextPath()  +"/";
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    HttpSession session = request.getSession();
    //获取请求地址
    String path = request.getServletPath();
    String account = (String) session.getAttribute("account");
    //获取请求地址+根目录
    StringBuffer server = request.getRequestURL();
    //直接放行js.css.jpg等静态资源
    if(server.toString().contains(".css") || server.toString().contains(".js") || server.toString().contains(".png")||server.toString().contains(".bmp")){
        filterChain.doFilter(request,response);
    }

    //防止用户不登录直接访问主页
    if(path.indexOf("main") > -1 && account ==null){
        response.sendRedirect(basePath+"login/index");
    }
    //用户初次登入系统
    if(path.indexOf("index") > -1 || path.indexOf("main") > -1){
        filterChain.doFilter(request,response);
        return;
    }
    //用户尚未登录时返回登录界面
    if(account == null || "".equals(account)){
        response.sendRedirect(basePath+"login/index");
    }else{
        filterChain.doFilter(request,response);
    }
}

public void destroy() {

}

}
配置登陆过滤器

<1filter>
<1filter-name>login
<1filter-class>com.honger.common.LoginFilter

<1filter-mapping>
<1filter-name>login
<1url-pattern>/*

你可能感兴趣的:(spring下登录过滤器的实现)