Java 过滤器Filter,Java Filter 不拦截某些请求 Java 过滤器支持Ajax请求

================================ ©Copyright 蕃薯耀 2020-01-10 https://www.cnblogs.com/fanshuyao/ 一、Java权限过滤器,如登录过滤 增加了配置文件,配置不拦截的请求,可以自...

================================

©Copyright 蕃薯耀 2020-01-10

https://www.cnblogs.com/fanshuyao/

一、Java权限过滤器,如登录过滤

增加了配置文件,配置不拦截的请求,可以自定义不拦截的规则,有三种:

1、不拦截包含/service/的请求(*/service/*)

2、不拦截以aaa/bbb/开头的请求(aaa/bbb/*)

3、不拦截以/ccc/aa.action结尾的请求(*/ccc/aa.action)

过滤器代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SessionFilter implements Filter {
    protected final Log logger = LogFactory.getLog(SessionFilter.class);
    private Set<String> unFilterSet = new HashSet<String>();
    
    @Override
    public void init(FilterConfig config) throws ServletException {
        InputStream in = null;
        BufferedReader reader = null;
        try {
            in = SessionFilter.class.getClassLoader().getResourceAsStream("sessionUnFilter.properties");
            if(in != null){
                reader = new BufferedReader(new InputStreamReader(in));
                String lineText = null;
                logger.info("=====不拦截的匹配规则有:");
                while((lineText = reader.readLine()) != null){
                    if(!StringUtils.isBlank(lineText) && (!lineText.trim().startsWith("#"))){//过滤掉空行和注释行
                        logger.info("=====" + lineText);
                        unFilterSet.add(lineText);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        logger.info("SessionFilter init()");
    }
    
    @Override
    public void destroy() {
        logger.info("SessionFilter destroy()");
    }
    
    /**
     * 如果请求链接符合不拦截的匹配,返回true
     * @param unFilterSet
     * @param requestURI
     * @return
     */
    public boolean isPass(Set<String> unFilterSet, String requestURI){
        logger.info("=====requestURI = "+requestURI);
        if(unFilterSet != null && unFilterSet.size() > 0){
            for (String unFilterUri : unFilterSet) {
                if(!StringUtils.isBlank(unFilterUri)){
                    unFilterUri = unFilterUri.trim();
                    if(unFilterUri.equals(requestURI)){
                        return true;
                    }else if(unFilterUri.startsWith("*") && unFilterUri.length() > 1 && unFilterUri.endsWith("*")){
                        String text = unFilterUri.substring(1, (unFilterUri.length() - 1));
                        //logger.info("=====contains text = " + text);
                        if(requestURI.contains(text)){
                            return true;
                        }
                    }else if(unFilterUri.startsWith("*") && !unFilterUri.endsWith("*")){
                        String text = unFilterUri.substring(1, (unFilterUri.length()));
                        //logger.info("=====endsWith text = " + text);
                        if(requestURI.endsWith(text)){
                            return true;
                        }
                    }else if(!unFilterUri.startsWith("*") && unFilterUri.endsWith("*")){
                        String text = unFilterUri.substring(0, (unFilterUri.length() - 1));
                        //logger.info("=====startsWith text = " + text);
                        if(requestURI.startsWith(text)){
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
            FilterChain chain) throws IOException, ServletException {
        
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        
        boolean isAjaxRequest = false;//判断是否Ajax请求
        if(!StringUtils.isBlank(req.getHeader("x-requested-with")) && req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
            isAjaxRequest = true;
        }
         UserInfo userInfo = null;
        try {
            userInfo = SecurityExtApi.getUserInfo(req);
        } catch (GeneralFailureException e) {
            e.printStackTrace();
        }
         if(userInfo != null && !StringUtils.isBlank(userInfo.getUserID())){
             chain.doFilter(req, res);
         }else{
             String requestURI = req.getRequestURI();
             //logger.info("=====requestURI = "+requestURI);
             if(requestURI.endsWith(".js") || requestURI.endsWith(".css") || requestURI.endsWith(".png") 
                     || requestURI.endsWith(".jpg") || requestURI.endsWith(".jpeg") || requestURI.endsWith(".gif")
                     || requestURI.endsWith(".ico")){
                 chain.doFilter(req, res);
                 return;
             }else if(isPass(unFilterSet, requestURI)){
                 chain.doFilter(req, res);
                 return;
             }else{
                 String msg = "登录已失效,请刷新页面或重新登录";
                 logger.info("=====" + msg);
                 if(isAjaxRequest){//Ajax请求结果处理
                     res.setContentType("application/json;charset=GBK");
                     res.setCharacterEncoding("GBK");
                     res.setHeader("error_code", "-999");
                     res.setHeader("error_msg", "The login is timeout, please login again!");
                     throw new RuntimeException(msg);//需要增加Ajax异常处理js全局配置文件ajax.config.js
                 }else{
                     res.sendRedirect("/");
                 }
             }
         }
    }
}


不拦截请求配置文件(sessionUnFilter.properties)如下:

#配置说明:
#*/services/* :不拦截包含/services/路径的
#/aa/startwith/* :不拦截以/aa/startwith/开头的
#*/endwith/end.jsp :不拦截以/endwith/end.jsp结尾的

/pro_name/aaa/login_local.jsp
/pro_name/bbb/ccc.action
*/services/*

Ajax请求处理需要增加一个js的全局处理配置文件

$(document).ajaxError(function(event,XHR){
    var error_code = XHR.getResponseHeader("error_code");
    var error_msg = XHR.getResponseHeader("error_msg");
    if(error_code != null && error_code != undefined){
        if("-999" == error_code){
            error_msg = "异常信息:登录已失效,请重新登录或刷新页面";
        }else{
            error_msg = "异常信息:"+ error_msg;
        }
    error_code = "异常代码:"+error_code;
    var error_tip = error_code +"<p>" + error_msg;
    top.$.messager.alert('异常提示:',error_tip,'error');
    }
});    

(如果你觉得文章对你有帮助,欢迎捐赠,^_^,谢谢!) 

================================

©Copyright 蕃薯耀 2020-01-10

https://www.cnblogs.com/fanshuyao/

  • 发表于 2020-01-10 15:21
  • 阅读 ( 224 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除