Java Filter does not block certain requests. Java Filter supports Ajax requests

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

Copyright 2020-01-10

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

 

1, Java permission filter, such as login filter

Configuration files are added to configure requests that are not intercepted. You can customize the rules that are not intercepted. There are three types:

1. Do not block requests containing / service / (* / service / *)

2. Requests starting with aaa/bbb / are not blocked (aaa/bbb / *)

3. Do not block requests ending with / ccc/aa.action (* / ccc/aa.action)

The filter code is as follows:

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("=====The matching rules not blocked are:");
                while((lineText = reader.readLine()) != null){
                    if(!StringUtils.isBlank(lineText) && (!lineText.trim().startsWith("#"))){//Filter out empty lines and comment lines
                        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()");
    }
    
    /**
     * Returns true if the requested link matches a match that is not blocked
     * @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;//Judge whether Ajax request
        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 = "Login has failed. Please refresh the page or log in again";
                 logger.info("=====" + msg);
                 if(isAjaxRequest){//Ajax Request result processing
                     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);//Need to increase Ajax exception handling js Global profile ajax.config.js
                 }else{
                     res.sendRedirect("/");
                 }
             }
         }
    }
}

 


Do not block the request configuration file (sessionUnFilter.properties) as follows:

#Configuration Description:
#*/services/* : Do not block the
#/aa/startwith/* : Do not block those starting with / aa/startwith /
#*/endwith/end.jsp : No interception/endwith/end.jsp Ending

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

 

Ajax request processing needs to add a js global processing configuration file

$(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 = "Exception information: login is invalid, please login again or refresh the page";
        }else{
            error_msg = "Exception information:"+ error_msg;
        }
    error_code = "Exception code:"+error_code;
    var error_tip = error_code +"<p>" + error_msg;
    top.$.messager.alert('Abnormal prompt:',error_tip,'error');
    }
});    

 

 

If you think the article is helpful to you, welcome to donate  

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

Copyright 2020-01-10

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

Keywords: Java Apache JSP JSON

Added by kellerkind on Fri, 10 Jan 2020 19:33:30 +0200