拦截器

作者: 沐浴中的眼泪 | 来源:发表于2020-03-29 09:53 被阅读0次

    1、添加类实现HandlerInterceptor

    public class RouteInterceptor implements HandlerInterceptor {

        @Override

        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

            response.setCharacterEncoding("UTF-8");

            response.setContentType("application/json; charset=utf-8");

            try {

                PrintWriter printWriter = response.getWriter();

                printWriter.append(new ObjectMapper().writeValueAsString(new Protocol(-1, "您无此操作权限")));

                return false;

            } catch (Exception e) {

                e.printStackTrace();

                response.sendError(500);

                return false;

            }

        }

        @Override

        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

        }

        @Override

        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

        }

    }

    2、拦截器返回Json数据-- response赋值

    response.setCharacterEncoding("UTF-8");

    response.setContentType("application/json; charset=utf-8");

    PrintWriter printWriter = response.getWriter();

    printWriter.append(new ObjectMapper().writeValueAsString(new Protocol(-1, "您无此操作权限")));

    3、配置拦截器 --  @Configuration

    @Configuration

    public class WebAppConfig extends WebMvcConfigurerAdapter {

        // 多个拦截器组成一个拦截器链

        // addPathPatterns 用于添加拦截规则

        // excludePathPatterns 用户排除拦截

        @Override

        public void addInterceptors(InterceptorRegistry registry) {

            registry.addInterceptor(new RouteInterceptor())   // 添加拦截器

                    .addPathPatterns("/**")   //  拦截所有请求

                    .excludePathPatterns("/user/**", "/system/**", "/base/**");   //对应的不拦截的请求

        }

    }

    相关文章

      网友评论

          本文标题:拦截器

          本文链接:https://www.haomeiwen.com/subject/ofjyuhtx.html