ASP源码.NET源码PHP源码JSP源码JAVA源码DELPHI源码PB源码VC源码VB源码Android源码
当前位置:首页 >> 网络编程 >> 其他编程教程 >> Java Filter 不拦截某些请求,Java Filter支持Ajax请求

Java Filter 不拦截某些请求,Java Filter支持Ajax请求(1/2)

来源:网络整理     时间:2018-10-20     关键词:

本篇文章主要介绍了" Java Filter 不拦截某些请求,Java Filter支持Ajax请求",主要涉及到方面的内容,对于其他编程教程感兴趣的同学可以参考一下: Java 过滤器Filter,Java Filter 不拦截某些请求Java 过滤器支持Ajax请求==============================...

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

Java 过滤器支持Ajax请求

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

?Copyright 蕃薯耀 2018年10月19日

http://fanshuyao.iteye.com/

一、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的全局处理配置文件(全部内容见附件):

相关图片

相关文章