自定义注解实例

22 篇文章 0 订阅

1.定义一个全局注解:

/**
 * 要求登录<br>
 * 要求登录注解
 *
 */
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface NeedLogin {
    boolean value();
}

@Target({ ElementType.METHOD, ElementType.TYPE })
表示的是注解可以使用的范围,这里用于描述方法和 描述类、接口(包括注解类型) 或enum声明

@Retention(RetentionPolicy.RUNTIME)
定义了该Annotation被保留的时间长短:在运行时有效

@Documented
表示是一个公用注解

上面已经定义好了一个自定义注解了

 @SuppressWarnings("unchecked")
    @RequestMapping("toJobList")
    @NeedLogin(true)
    public ModelAndView toAmJobList(HttpServletRequest request, ModelAndView view, HttpSession session) {

可以在controller上添加
@NeedLogin(true)这个注解
<pre name="code" class="java"> @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 访问的链接
        String requestUrl = request.getRequestURI();
        // 上下文路径
        String contentPath = request.getContextPath();
        // 去掉uri中的上下文路径 后的 url ,数据库中配置的url 都是 没有上下文路径的
        String shortRequetUri = requestUrl.replace(contentPath, "");
        HandlerMethod methodhandler = (HandlerMethod) handler;
        // 方法
        Method method = methodhandler.getMethod();
        // 获取求头
        String requestheader = request.getHeader("X-Requested-With"); // Ajax请求

        // 注入 权限接口实现
        if (null == permissionService) {
            ServletContext context = request.getServletContext();
            ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context);
            permissionService = (PermissionService) ac.getBean("permissionService");
        }

        if (null == crmOperatorGwService) {
            ServletContext context = request.getServletContext();
            ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context);
            crmOperatorGwService = (CrmOperatorGwService) ac.getBean("crmOperatorGwService");
        }

        // 获取 操作者角色 的注解
        Role role = methodhandler.getBean().getClass().getAnnotation(Role.class);
        // 获取方法上的 是否 登录注解
        NeedLogin needLoginAnnotation = method.getAnnotation(NeedLogin.class);


 

这个是拦截器中的部分代码,我们在这里通过判断

@NeedLogin是否包含这个注解去完成我们自己的逻辑


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值