首页 文章资讯内容详情

springMVC之mvc:interceptors拦截器的用法

2026-06-01 2 花语

本文内容纲要:

1.配置拦截器

在springMVC.xml配置文件增加:

1<mvc:interceptors> 2<!--日志拦截器--> 3<mvc:interceptor> 4<mvc:mappingpath="/**"/> 5<mvc:exclude-mappingpath="/static/**"/> 6<beanclass="拦截器java代码路径"/> 7</mvc:interceptor> 8</mvc:interceptors>

说明:

1)mvc:mapping拦截器路径配置

2)mvc:exclude-mapping拦截器不需要拦截的路径

2、样例:

1publicclassLogsInterceptorextendsHandlerInterceptorAdapter{ 2 3privatestaticfinalLoggerlogger=LoggerFactory.getLogger(LogsInterceptor.class); 4 5privateNamedThreadLocal<String>logContext=newNamedThreadLocal<String>("log-id"); 6 7@Autowired 8privateTLogDaologDao; 9 10/** 11*preHandle方法是进行处理器拦截用的,顾名思义,该方法将在Controller处理之前进行调用, 12*SpringMVC中的Interceptor拦截器是链式的,可以同时存在多个Interceptor, 13*然后SpringMVC会根据声明的前后顺序一个接一个的执行, 14*而且所有的Interceptor中的preHandle方法都会在Controller方法调用之前调用。 15*SpringMVC的这种Interceptor链式结构也是可以进行中断的, 16*这种中断方式是令preHandle的返回值为false,当preHandle的返回值为false的时候整个请求就结束了。 17*/ 18@Override 19publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{ 20Stringhost=request.getRemoteHost(); 21Stringurl=request.getRequestURI(); 22TLogEntityentity=newTLogEntity(); 23entity.setCreateTime(newTimestamp(System.currentTimeMillis())); 24entity.setCreateUser("admin"); 25entity.setIpAddress(host); 26entity.setLogUrl(url); 27entity.setIsSuccess("N"); 28logDao.save(entity); 29logContext.set(entity.getLogId()); 30 31logger.debug("IP为---->>>"+host+"<<<-----访问了系统"); 32returntrue; 33} 34 35/** 36*这个方法只会在当前这个Interceptor的preHandle方法返回值为true的时候才会执行。 37*postHandle是进行处理器拦截用的,它的执行时间是在处理器进行处理之后,也就是在Controller的方法调用之后执行, 38*但是它会在DispatcherServlet进行视图的渲染之前执行,也就是说在这个方法中你可以对ModelAndView进行操作。 39*这个方法的链式结构跟正常访问的方向是相反的,也就是说先声明的Interceptor拦截器该方法反而会后调用, 40*这跟Struts2里面的拦截器的执行过程有点像, 41*只是Struts2里面的intercept方法中要手动的调用ActionInvocation的invoke方法, 42*Struts2中调用ActionInvocation的invoke方法就是调用下一个Interceptor或者是调用action, 43*然后要在Interceptor之前调用的内容都写在调用invoke之前,要在Interceptor之后调用的内容都写在调用invoke方法之后。 44*/ 45@Override 46publicvoidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,ModelAndViewmodelAndView)throwsException{ 47} 48 49/** 50*该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行。 51*该方法将在整个请求完成之后,也就是DispatcherServlet渲染了视图执行,这个方法的主要作用是用于清理资源的, 52*/ 53@Override 54publicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex){ 55Stringhost=request.getRemoteHost(); 56StringlogId=logContext.get(); 57TLogEntityentity=logDao.findOne(logId); 58entity.setIsSuccess("Y"); 59logDao.save(entity); 60 61logger.debug("IP为---->>>"+host+"<<<-----访问成功"); 62} 63 64}

在这个拦截器中,在方法执行前可以做session或权限的。

本文内容总结:

原文链接:https://www.cnblogs.com/lcngu/p/7096597.html