拦截器

2020-03-29  本文已影响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/**");   //对应的不拦截的请求

    }

}

上一篇下一篇

猜你喜欢

热点阅读