spring boot拦截器使用(HandlerInterceptorAdapter)

[size=medium][color=red][b]1.继承HandlerInterceptorAdapter[/b][/color][/size]

public class MyInterceptor extends HandlerInterceptorAdapter{

private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
/**
* 请求前执行该方法
*
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("请求前");
if(request.getSession() == null || request.getSession().getAttribute("user_info")==null){
System.out.println("登陆超时,请重新登陆!");
logger.error("登陆超时,请重新登陆!");
return false;
}
System.out.println(request.getRequestURL());
System.out.println(request.getRemoteHost());
return true ;
}
/**
* 执行完成后执行该方法
*
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("请求后");
}
}


[size=medium][color=red][b]2.将拦截器加入全局WebMvcConfigurerAdapter中[/b][/color][/size]

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor());
}
}

你可能感兴趣的:(spring,sprint,boot)