1.核心API HanlerInterceptor WebMvcConfigureAdaptor
2.流程:
a.定义拦截器(实现HanlerInterceptor接口,或继承HandlerInterceptorAdaptor类);
默认方法中绑定了请求和响应可在请求和响应中相应的处理
M:preHandle postHandle
request.setAttribute("tango","beauty");
b.将拦截器加入应用的上下文环境,实现WebMvcConfigureAdaptor
M:addInterceptors(Registry registery)方法
registery.addInterceptor(自定义的拦截器);
3.示例代码
自定义拦截器
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class TangoInteceptor extends HandlerInterceptorAdapter{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
long startTime = System.currentTimeMillis();
response.getWriter().println("请求开始!");
request.setAttribute("startTime",startTime);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
long endtime=System.currentTimeMillis();
Long startTime =(Long) request.getAttribute("startTime");
System.out.println("本次请求共用了时间"+new Long(endtime-startTime)+"ms");
response.getWriter().println("请求结束!"+"本次请求共用了时间"+new Long(endtime-startTime)+"ms");
}
}
注册拦截器
@TangoConfig("com.tango.spring.Intercepter")
public class InterCeptorConfig extends WebMvcConfigurerAdapter{
@Bean
public TangoInteceptor tangoInteceptor() {
return new TangoInteceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(tangoInteceptor());
}
}
测试的Conttroller
@RestController
public class TangoController {
@RequestMapping("/tango")
public void tangoTest() {
System.out.println("世界真奇妙");
}
}