spring boot实现过滤器和拦截器demo
整理文档,搜刮出一个springboot实现过滤器和拦截器demo,稍微整理精简一下做下分享。
拦截器定义:
@WebServlet publicclassActionInterceptorimplementsHandlerInterceptor{ @Override publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler) throwsException{ //System.out.println(">>>MyInterceptor1>>>>>>>在请求处理之前进行调用(Controller方法调用之前)"); //获取系统时间 Calendarca=Calendar.getInstance(); inthour=ca.get(Calendar.HOUR_OF_DAY); //设置限制运行时间0-4点 if(hour<4){ returntrue; } returnfalse; } @Override publicvoidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler, ModelAndViewmodelAndView)throwsException{ //System.out.println(">>>MyInterceptor1>>>>>>>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)"); } @Override publicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex) throwsException{ //System.out.println(">>>MyInterceptor1>>>>>>>在整个请求结束之后被调用,也就是在DispatcherServlet //渲染了对应的视图之后执行(主要是用于进行资源清理工作)"); } }
拦截器使用: 关于注解我使用的是@Component 其实也可能声明成配置
@Component publicclassApplicationConfig{extendsWebMvcConfigurerAdapter @Override publicvoidaddInterceptors(InterceptorRegistryregistry){ //多个拦截器组成一个拦截器链 //addPathPatterns用于添加拦截规则 //excludePathPatterns用户排除拦截 registry.addInterceptor(newActionInterceptor()).addPathPatterns("/service/extract/json/**"); super.addInterceptors(registry); } }
过滤器:
定义:
publicclassActionFilterimplementsFilter{ @Override publicvoidinit(FilterConfigfilterConfig)throwsServletException{ } @Override publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain) throwsIOException,ServletException{ //获取系统时间 Calendarca=Calendar.getInstance(); inthour=ca.get(Calendar.HOUR_OF_DAY); //设置限制运行时间0-4点 if(hour<4){ HttpServletResponsehttpResponse=(HttpServletResponse)response; httpResponse.setCharacterEncoding("UTF-8"); httpResponse.setContentType("application/json;charset=utf-8"); //消息 Map<String,Object>messageMap=newHashMap<>(); messageMap.put("status","1"); messageMap.put("message","此接口可以请求时间为:0-4点"); ObjectMapperobjectMapper=newObjectMapper(); StringwriteValueAsString=objectMapper.writeValueAsString(messageMap); response.getWriter().write(writeValueAsString); }else{ chain.doFilter(request,response); } } @Override publicvoiddestroy(){ } }
使用:
@Component publicclassApplicationConfig{ @Bean publicFilterRegistrationBeanfilterRegistrationBean(){ FilterRegistrationBeanregistrationBean=newFilterRegistrationBean(); ActionFilteractionFilter=newActionFilter(); registrationBean.setFilter(actionFilter); List<String>urlPatterns=newArrayList<String>(); urlPatterns.add("/service/extract/json/*"); registrationBean.setUrlPatterns(urlPatterns); returnregistrationBean; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。