什么是拦截器
拦截器(Interceptor): 用于在某个方法被访问之前进行拦截,然后在方法执行之前或之后加入某些操作,它通过动态拦截Action调用的对象,允许开发者定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。
拦截器作用
拦截用户的请求并进行相应的处理,比如:判断用户是否登陆,记录日志信息等
SpringBoot添加拦截器的方法
1、定义拦截器
package com.test.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class MyInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("MyInterceptor preHandle request..."+request);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor postHandle request..."+request);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("MyInterceptor afterCompletion request..."+request);
}
}
2、配置拦截器
package com.test.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootConfiguration
public class MySpringConfig extends WebMvcConfigurerAdapter{
@Autowired
private MyInterceptor myIntcpt;
@Override
public void addInterceptors(InterceptorRegistry registry)
{
registry.addInterceptor(myIntcpt).addPathPatterns("/**");
}
}
日志信息
2018-12-18 21:32:29.866 DEBUG 18168 --- [nio-6060-exec-9] c.t.mapper.OrgModelMapper.getChildFunc : ==> Parameters: 6(Integer)
2018-12-18 21:32:29.884 DEBUG 18168 --- [nio-6060-exec-9] c.t.mapper.OrgModelMapper.getChildFunc : <== Total: 0
2018-12-18 21:32:29.887 DEBUG 18168 --- [nio-6060-exec-9] c.t.mapper.OrgModelMapper.getChildFunc : ==> Preparing: select * from T_FUNCTION where parentid=? order by priority
2018-12-18 21:32:29.887 DEBUG 18168 --- [nio-6060-exec-9] c.t.mapper.OrgModelMapper.getChildFunc : ==> Parameters: 5(Integer)
2018-12-18 21:32:29.891 DEBUG 18168 --- [nio-6060-exec-9] c.t.mapper.OrgModelMapper.getChildFunc : <== Total: 0
MyInterceptor postHandle request...org.apache.catalina.connector.RequestFacade@5a31e8a0
MyInterceptor afterCompletion request...org.apache.catalina.connector.RequestFacade@5a31e8a0