定义一个配置类
@Configuration
public class MySpringMVC implements WebMvcConfigurer {
@Autowired
private MyInterceptor myInterceptor;
/**
* 视图映射
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/login").setViewName("login");
registry.addViewController("/helloword").setViewName("login");
}
/**
* 注册拦截器,也就是使自己的拦截器生效
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/test_interceptor");
}
}
定义拦截器,并加上@Component注解注入ioc容器
/**
* 定义自己的拦截器
*/
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//通过request.getParameter("name");获取控制方法的参数值
String name = request.getParameter("name");
//拿到值后做判断
if (name.equals("chen")){
//放行
return true;
}
//拦截
return false;
}
}
这里展示一下控制方法
@RestController
public class Controller {
@GetMapping("/*****")
public String test_interceptor(@RequestParam("name") String name){}
}