springmvc 自定义注解

https://www.cnblogs.com/yingsong/p/8508700.html

1. 自定义一个注解

复制代码
@Documented //文档生成时,该注解将被包含在javadoc中,可去掉
@Target(ElementType.METHOD)//目标是方法 
@Retention(RetentionPolicy.RUNTIME) //注解会在class中存在,运行时可通过反射获取  @Inherited public @interface AuthLoginAnnotation {
  /**
     * 检查是否已登录(注解的参数)
     *
     * @return true-检查;默认不检查为false
     */ boolean check() default false; }

  • 注解方法不能有参数。
  • 注解方法的返回类型局限于原始类型,字符串,枚举,注解,或以上类型构成的数组。
  • 注解方法可以包含默认值。
  • 注解可以包含与其绑定的元注解,元注解为注解提供信息,有四种元注解类型:
 
 

  1. @Documented – 表示使用该注解的元素应被javadoc或类似工具文档化,它应用于类型声明,类型声明的注解会影响客户端对注解元素的使用。如果一个类型声明添加了Documented注解,那么它的注解会成为被注解元素的公共API的一部分。

 
 

  2. @Target – 表示支持注解的程序元素的种类,一些可能的值有TYPE, METHOD, CONSTRUCTOR, FIELD等等。如果Target元注解不存在,那么该注解就可以使用在任何程序元素之上。

 
 

  3. @Inherited – 表示一个注解类型会被自动继承,如果用户在类声明的时候查询注解类型,同时类声明中也没有这个类型的注解,那么注解类型会自动查询该类的父类,这个过程将会不停地重复,直到该类型的注解被找到为止,或是到达类结构的顶层(Object)。

 
 

  4. @Retention – 表示注解类型保留时间的长短,它接收RetentionPolicy参数,可能的值有SOURCE(源文件中起作用), CLASS, 以及RUNTIME(保留到运行时起作用)。

 
复制代码

2. 定义一个相应的拦截器,在springMVC配置文件中进行配置

  拦截器:

  spring为我们提供了org.springframework.web.servlet.handler.HandlerInterceptorAdapter这个适配器,继承此类,可以非常方便的实现自己的拦截器。

       可以根据我们的需要重写preHandle(预处理)、postHandle后处理(调用了Service并返回ModelAndView,但未进行页面渲染)、afterCompletion返回处理(已经渲染了页面)。

复制代码
public class AuthLoginInteceptor extends HandlerInterceptorAdapter {
    @Autowired
    UserInfoService userInfoService ;
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HandlerMethod methodHandler=(HandlerMethod) handler; AuthCheckAnnotation auth=methodHandler.getMethodAnnotation(AuthCheckAnnotation.class);      //如果@AuthLoginAnnotation (check=false) 这里的auth为false,即不用进行拦截验证,@AuthCheckAnnotation默认为前面定义的true   if(auth!=null&&!auth.check()){ if(!isLogin(request)){
        request.getRequestDispatcher("login.do").forward(request, response);
        return false;
       } }      return true; } }
复制代码

3. 在springMVC.xml文件中添加拦截器

   <mvc:interceptors>
            <mvc:interceptor>
            <mvc:mapping path="/*.do"  />
            <bean  class="com.k.common.interceptor.AuthLoginInteceptor "/>        
        </mvc:interceptor>
    </mvc:interceptors>

4. 在springMVC controller中使用实例

复制代码
    @AuthLoginAnnotation(check=true)
    @RequestMapping("tomember.do")
    @ResponseBody
    public Object toMember(HttpServletRequest request,HttpServletResponse response){
        .......
        return Ret.toJson(responseBody);
    }
复制代码

 参考一篇ImportNew中简单讲解JAVA注解的文章:http://www.importnew.com/14479.html

猜你喜欢

转载自www.cnblogs.com/zhoading/p/12194851.html