1.第一步创建一个类实现HandlerInterceptor接口,重写接口的方法
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 IntercepterTest implements HandlerInterceptor{
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("拦截器MyInterceptor------->3、请求结束之后被调用,主要用于清理工作。");
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("拦截器MyInterceptor------->2、请求之后调用,在视图渲染之前,也就是Controller方法调用之后");
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String url = request.getServletPath();//url====="/failed"
System.out.println("url"+url);
if("/login".equals(url)) {
return true;//放行
}
return false;//拦截
}
}
2.第二步:注册拦截器。创建一个配置类并继承 WebMvcConfigurerAdapter。重写 addInterceptors 方法。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.example.intercepter.IntercepterTest1;
@Configuration
public class WebAdepter extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new IntercepterTest()).addPathPatterns("/**");//配置拦截路径
super.addInterceptors(registry);
}
}
测试controller
@RequestMapping("/login")
public Map<String, String> intercepter(){
Map<String, String> map = new HashMap<>();
map.put(“a”, “d”);
map.put(“b”, “c”);
return map;
}
测试已经通过 如果访问路径是不是/login
如果访问路径是/login