import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class Lanjieqi implements HandlerInterceptor {
//controller执行之前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println(request.getRequestURI()+"begin");
return true;
}
//controller执行中
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("beginging");
}
//controller执行结束
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("执行结束");
}
}
这个配置拦截器的,说明一下,在preeHandle中返回的布尔值代表要不要拦截,这个HandlerInterceptor主要是用来拦截请求的,拦截方法是使用MethodInterceptor,例如在登陆验证中,如果验证失败,就应该返回false,所以看具体需求
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class Lanjieiq_config implements WebMvcConfigurer {
@Autowired
private lanjieqi lanjieqi;
@Override
public void addInterceptors(InterceptorRegistry registry)
{
registry.addInterceptor(lanjieqi).addPathPatterns("/books/bookMap");
}
}
这个是配置需要拦截的路径,注意需要依赖注入的对象在当中,然后在添加拦截的路径,controller中配置好接口后调用,下面是没有拦截的情况
这是拦截的,改成false即可
两个空方法没有调用,主要实现的是PreHandle来处理是否拦截