首页 > 其他分享 >springboot 自定义注解拦截器

springboot 自定义注解拦截器

时间:2022-09-02 16:01:33浏览次数:82  
标签:httpServletRequest 拦截器 return springboot 自定义 httpServletResponse token public lo

参考: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);
    }

 

标签:httpServletRequest,拦截器,return,springboot,自定义,httpServletResponse,token,public,lo
From: https://www.cnblogs.com/person008/p/16650220.html

相关文章

  • SpringBoot多数据源配置
    在实际的开发或者线上环境中,一般都不仅仅是一个数据库走天下,而是根据业务进行拆分多个数据库。另外,在日常开发中我们都是以单个数据库进行开发,在小型项目中是完全能够满足......
  • 为什么我要迁移SpringBoot到函数计算
    前言为什么要迁移?我们的业务有很多对外提供服务的RESTfulAPI,并且要执行很多不同的任务,例如同步连锁ERP中的商品信息到美团/饿了么等平台,在线开发票等。由于各种API......
  • 基于函数计算自定义运行时快速部署一个 springboot 项目 什么是函数计算?
    什么是函数计算?函数计算是事件驱动的全托管计算服务。使用函数计算,您无需采购与管理服务器等基础设施,只需编写并上传代码。函数计算为您准备好计算资源,弹性地可靠地运行任......
  • vue+Springboot下载文件
    前端代码<el-buttontype="primary"@click="dowload2('1662023440868上传测试.jpg')">下载</el-button>js代码dowload2(msg){lethref="http://......
  • SpringBoot整合Redis
    14、SpringBoot整合Redis14.1、概述SpringBoot操作数据库:spring-data,jpa,jdbc,mongodb,redisSpringData也是和SpringBoot齐名的项目!说明:在SpringBoot2.x之后,原来使用的jed......
  • springboot项目使用jsp
    异常问题场景提示:这里简述项目相关背景springboot课堂学习问题详情提示:这里描述项目中遇到的问题jsp无法访问原因分析提示:这里填写问题的分析没有jsp解......
  • elementui对于vue表单自定义校验
    在<el-form-itemlabel="原因"prop="reson":rules="条件==值?[{required:true,message:'原因不能为空',trigger:'blur'}]:[{requ......
  • 使用 CSS 自定义鼠标光标
    使用CSS自定义鼠标光标你好,互联网上令人惊叹的人。希望你们都做得很好。在本文中,我们将讨论CSS光标属性。我们将在这里看到有多少类型的值与可用的游标属性相关联。......
  • 自定义分页器
    自定义分页器针对上一小节批量插入的数据,我们在前端展示的时候发现一个很严重的问题,一页展示了所有的数据,数据量太大,查看不方便针对数据量大但又需要全部展示给用户观看......
  • Flask 学习-35.restful-full 自定义错误内容 error_msg 使用
    前言当接口请求参数不合法的,可以给前端返回报错原因,给个友好的返回消息,在add_argument()中可以通过help参数来定义错误信息每个字段的错误消息可以使用help参数(Requ......