欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-09 18:04:34
©Copyright 蕃薯耀 2020-01-10 https://www.cnblogs.com/fanshuyao/ 一、Java权限过滤器,如登录过滤 增加了配置文件,配置不拦截的请求,可以自定义不拦截的规则,有三种: 1、不拦截包含/service/的请求(*/service/*) 2、不拦 ......

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

©copyright 蕃薯耀 2020-01-10

 

一、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');
    }
});    

 

 

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

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

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

©copyright 蕃薯耀 2020-01-10