在Java开发过程中,拦截器的使用是必不可少的,那拦截器作用是什么呢?
拦截器:通过特定条件对请求进行拦截,并作出对应回应。
拦截器该怎么使用呢?
一、创建一个拦截器
public class HandlerInterceptor implements org.springframework.web.servlet.HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("启动拦截器");
return false;
}
}
注:需要实现HandlerInterceptor接口,并且重写preHandle()方法。
HandlerInterceptor接口总共有三个方法,区别在于触发拦截器的时间不同:
preHandle()是在请求之前触发拦截器、
postHandle()是在请求之后触发拦截器、
afterCompletion()是在请求完成之后触发拦截器。
二、使用拦截器
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
String [] path={"/hello/**","/go/**"};
String [] Epath={"/user/go"};
registry.addInterceptor(new HandlerInterceptor()).addPathPatterns(path).excludePathPatterns(Epath);
}
}
注:这里是通过springboot框架完成的,@Configuration声明这个类为配置信息;
实现WebMvcConfigurer接口,并且重写addInterceptors()方法;
addInterceptor()方法指定拦截器对象、
addPathPatterns()方法指定拦截路径(可以是String类型、String[]类型)、
excludePathPatterns()方法指定不理解路径(可以是String类型、String[]类型)。
三、写测试代码
@Controller
public class MyController {
// 第一个方法
@RequestMapping(value = "/hello/one")
@ResponseBody
public String One(){
return "第一个方法";
}
// 第二个方法
@RequestMapping(value = "/user/go")
@ResponseBody
public String Two(){
return "第二个方法";
}
}
注:@Controller注解声明控制器。
四、测试拦截器
上面写了两个方法,访问路径分别是http://localhost:8080/hello/one和http://localhost:8080/user/go
http://localhost:8080/hello/one结果:
http://localhost:8080/user/go结果:
哪些地方会用到拦截器?
用处:最常见的就是用户登录功能了,当没有用户登录信息,就会进行拦截,阻止用户进一步操作。
源码:
https://github.com/Yuqn/Handlerinterceptor.git
上面就是关于拦截器的一些简单用法。
以上内容可能存在不足或错误,如有发现请指出来。