在java开发中,拦截器使用是很普遍的,最常用的就是登陆拦截了,然后并不是所有的请求我们都需要拦截,比如index页面的请求我们是不拦截的.通常情况下我们有两种方式:先贴出来springboot使用拦截器的case:
1.自定义拦截器,实现HandlerInterceptor ,也可以采用继承的方式(HandlerInterceptorAdapter),内容不重要,看过程
public class LoginHandlerInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
if (StringUtils.isEmpty(username) || !Objects.equals("123456",username)) {
request.setAttribute("msg","没有权限");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else {
return true;
}
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
2.配置我们自定义的拦截器
@Configuration
public class MyConfigurerAdapter extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("*").excludePathPatterns("/index","/","/user/login");
super.addInterceptors(registry);
}
}
第一种方式就是使用interceptor的excludePatterns来去除我们不要验证的请求
第二种方式是使用注解的方式(虽然这个麻烦一点点,但是使用方便)
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UnAuthRequest {
}
然后我们自己的拦截器就需要改一下
public class LoginHandlerInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
UnAuthRequest annotation = method.getAnnotation(UnAuthRequest.class);
if (Objects.nonNull(annotation)) {
return true;
}
String username = (String) session.getAttribute("username");
if (StringUtils.isEmpty(username) || !Objects.equals("123456",username)) {
request.setAttribute("msg","没有权限");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else {
return true;
}
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
这样的话,我们只需要将注解贴在我们不需要拦截的请求上就行了,使用起来很方便.