- 前言
- 一、拦截器使用步骤
- 1.拦截器配置
- 2.拦截器处理逻辑
- 总结
前言 因为项目需要,所以这里自定义了一个拦截器来进行部分路径的拦截,来进行相关验证
一、拦截器使用步骤 1.拦截器配置
代码如下(示例):
@Configuration public class InterceptorConfig implements WebMvcConfigurer { @Autowired private ApiInterceptor apiInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { ListexcludePathPatterns = new ArrayList<>(); excludePathPatterns.add("/VIID/System/Register"); excludePathPatterns.add("/VIID/System/UnRegister"); registry.addInterceptor(apiInterceptor) .addPathPatterns("/VIID @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception { boolean flag = false; if (flag ){ return true; }else { logger.info("---------------拦截请求----------------------"); logger.info(JSON.toJSONString(responseStatus)); logger.info("--------------------------------------------"); returnAjaxError(httpServletResponse, responseStatus); return false; } } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView){ } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } public void returnAjaxError(HttpServletResponse response, Object errorMsg){ PrintWriter writer = null; System.out.println("returnError"); System.out.println(errorMsg); try { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); writer = response.getWriter(); writer.append(JSON.toJSONString(errorMsg)); }catch (IOException ignored){ }finally { if (writer != null){ writer.close(); } } } }
总结 自定义拦截器还是比较简单的
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)