spring boot 配置Filter过滤器的方法
Filter过滤器是web开发中很重要的一个组件,下面以一个session登陆的例子介绍下springboot中如何使用Filter
首先要准备一个实现了Filter的接口的类SessionFilter:
importorg.slf4j.LoggerFactory; importjavax.servlet.*; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjavax.servlet.http.HttpSession; importjava.io.IOException; importjava.util.ArrayList; importjava.util.List; importjava.util.regex.Matcher; importjava.util.regex.Pattern; /** *Createdbymazhenhuaon2016/12/27. * *过滤器 */ publicclassSessionFilterimplementsFilter{ privatestaticfinalorg.slf4j.Loggerlogger=LoggerFactory.getLogger(SessionFilter.class); /** *封装,不需要过滤的list列表 */ protectedstaticListpatterns=newArrayList (); @Override publicvoidinit(FilterConfigfilterConfig)throwsServletException{ } @Override publicvoiddoFilter(ServletRequestservletRequest,ServletResponseservletResponse,FilterChainchain)throwsIOException,ServletException{ HttpServletRequesthttpRequest=(HttpServletRequest)servletRequest; HttpServletResponsehttpResponse=(HttpServletResponse)servletResponse; logger.info("aaaaaaaaaa"); Stringurl=httpRequest.getRequestURI().substring(httpRequest.getContextPath().length()); if(url.startsWith("/")&&url.length()>1){ url=url.substring(1); } if(isInclude(url)){ chain.doFilter(httpRequest,httpResponse); return; }else{ HttpSessionsession=httpRequest.getSession(); if(session.getAttribute("")!=null){ //session存在 chain.doFilter(httpRequest,httpResponse); return; }else{ //session不存在准备跳转失败 /*RequestDispatcherdispatcher=request.getRequestDispatcher(path); dispatcher.forward(request,response);*/ chain.doFilter(httpRequest,httpResponse); return; } } } @Override publicvoiddestroy(){ } /** *是否需要过滤 *@paramurl *@return */ privatebooleanisInclude(Stringurl){ for(Patternpattern:patterns){ Matchermatcher=pattern.matcher(url); if(matcher.matches()){ returntrue; } } returnfalse; } }
实际开发中往往有很多请求要直接请求进来,不需要鉴权登陆的,所以代码中过滤掉这种请求的代码,装进list就好了。
/** *配置过滤器 *@return */ @Bean publicFilterRegistrationBeansomeFilterRegistration(){ FilterRegistrationBeanregistration=newFilterRegistrationBean(); registration.setFilter(sessionFilter()); registration.addUrlPatterns("/*"); registration.addInitParameter("paramName","paramValue"); registration.setName("sessionFilter"); returnregistration; } /** *创建一个bean *@return */ @Bean(name="sessionFilter") publicFiltersessionFilter(){ returnnewSessionFilter(); }
经过上面这俩步的配置,过滤器基本上就可以了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。