随笔 - 195  文章 - 0  评论 - 5  阅读 - 20万

springboot 自定义注解拦截器

参考:https://blog.csdn.net/mxlgslcd/article/details/89155315

第一步:自定义注解

复制代码
@Target(ElementType.METHOD)// 可用在方法名上
@Retention(RetentionPolicy.RUNTIME)// 运行时有效
public @interface AppAccess {
    /**
     * 认证所使用的认证器
     */
    Class<? extends AuthFactory> authenticator();

}
复制代码

第二部:认证工厂

public abstract class AuthFactory {
    public abstract boolean auth(HttpServletRequest request, HttpServletResponse response, Object object) throws IOException;
}

第三步:拦截

复制代码
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    /**
     * 请求处理之前调用
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws IOException {
        log.info("请求地址:【{}】", httpServletRequest.getServletPath());
        //如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(AppAccess.class)) {
            AppAccess annotation = method.getAnnotation(AppAccess.class);
            Class<? extends AuthFactory> authenticator = annotation.authenticator();
            AuthFactory bean = SpringUtils.getBean(authenticator);
            return bean.auth(httpServletRequest, httpServletResponse, object);
        }
        return true;
    }
    /**
     * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
复制代码

第四步:认证

复制代码
@Component
@Slf4j
public class AppAuthenticator extends AuthFactory {

    @Autowired
    private RedisCache redisCache;
    private static String TOKEN = "APP_{IDENTITY}_TOKEN_{ID}";
    public static final String TOKEN_KEY = "Authorization";
    @Override
    public boolean auth(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws IOException {
        log.info("请求地址:【{}】", httpServletRequest.getServletPath());
        Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
        String join = MapUtil.join(parameterMap, ",", "=");
        log.info("请求参数:【{}】",join);
        //获取请求头的token
        String token = httpServletRequest.getHeader(TOKEN_KEY);
        log.info("token:{}", token);
        //响应
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        //认证
        if (StringUtils.isEmpty(token)) {
            log.info("token为空");
            httpServletResponse.getWriter().write(JSON.toJSONString(AjaxResult.error("登录过期!","")));
            return false;
        }
        自己业务----------
        return true;
    }
}
复制代码

第五步:验证

复制代码
/**
     * 推荐商户列表
     * @param userSearchVo
     * @return
     */
    @AppAccess(authenticator = AppAuthenticator.class)
    @GetMapping("/getMerchantList")
    public TableDataInfo getMerchantList(UserSearchVo userSearchVo){
        log.info("商户推荐 :{}", userSearchVo);
        startPage();
        List<UserMerchantRecommendVo> merchantList = baseMerchantService.selectMerchantList(userSearchVo);
        merchantList.stream().map(s -> {
            s.setDistance(distanceCovert(s.getDistance()));
            return s;
        }).collect(Collectors.toList());
        return getDataTable(merchantList);
    }
复制代码

 

posted on   大山008  阅读(1016)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示