拦截器
1.定义一个拦截器类
public class PassportInterceptor implements HandlerInterceptor { @Autowired public RedisOperator redisOperator; public static final String MOBILE_SMSCODE="mobile:smscode"; /** * 拦截请求,进入controller前进行拦截 * * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //获取用户IP String userIP = IPUtil.getRequestIp(request); //获取key boolean keyIsExist = redisOperator.keyIsExist(MOBILE_SMSCODE + ":" + userIP); if (keyIsExist){ System.out.println("短信发送频率过快!"); GraceExecption.display(ResponseStatusEnum.SMS_NEED_WAIT_ERROR); return false; } /** * true:放行 * false:拦截 */ return true; } /** * 请求访问controller之后,渲染视图之前 * * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * 请求访问controller之后,渲染视图之后 * * @param request * @param response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
2.将拦截器注册到spring容器中
拦截器配置类中,先将拦截器类注册到bean,然后用addInterceptors配置拦截器,配置需要拦截的路由
自定义异常
先定义一个自定义异常(继承RuntimeExecption)
定义一个自定义异常的封装类
定义自定义异常捕捉管理器
在拦截器中使用
⭐当拦截器中被拦截下来会抛出自定义异常