使用拦截器,过滤器,AOP完成鉴权

一:拦截器

1.定义拦截器
@Component
public class MyIntercepter implements HandlerInterceptor {
    @Override
    //原始方法调用前执行的内容,返回值为true表示放行,返回值为false表示不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if("".equals("token")||token ==null){
            Result result = new Result("您没有传token", 403, null);
            response.getWriter().write(result.toString());
            return  false;
        }
        if(!token.equals(Constants.TOKEN)){
            Result result = new Result("您传的参数有误", 401, null);
            response.getWriter().write(result.toString());
            return  false;
        }
        return true;
    }
}
2.配置拦截器
@Configuration
public class MyConfig implements WebMvcConfigurer {
    /**
     * 配置拦截规则与注入拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPattern 添加拦截规则 /** 拦截所有包括静态资源
        // excludePathPattern 排除拦截规则 所以我们需要放开静态资源的拦截
        registry.addInterceptor(new MyIntercepter())
                .addPathPatterns("/members/**","/managers/**")
                .excludePathPatterns("/css/**", "/fonts/**", "/images/**", "/js/**");
    }
}

二:过滤器

1.定义过滤器
@WebFilter(filterName = "MyFilter", urlPatterns = {"/members/*","/managers/*"})
public class MyFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String token = request.getHeader("token");

        if ("".equals(token) || token == null) {
            Result result = new Result("您没有传token", 403, null);
            response.getWriter().write(result.toString());
            return;
        }

        if (!token.equals(Constants.TOKEN)) {
            Result result = new Result("您传的token有误", 401, null);
            response.getWriter().write(result.toString());
            return;
        }
        //放行
        filterChain.doFilter(request, response);
    }
}
2.配置过滤器
@SpringBootApplication
@ServletComponentScan
public class MpdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(MpdemoApplication.class, args);
    }
}

三:AOP

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值