springMVC :HandlerInterceptorAdapter + 自定义注解 实现用户登入 的请求拦截器

版权声明:本文为博主搜索整合文章。 https://blog.csdn.net/weixin_37794901/article/details/79834004

sept1 自定义注解

                      @retention :Retention(保留)注解说明,这种类型的注解会被保留到哪个阶段. 有三个值{
1).RetentionPolicy.SOURCE —— 这种类型的Annotations只在源代码级别保留,编译时就会被忽略 
2).RetentionPolicy.CLASS —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略 

3).RetentionPolicy.RUNTIME —— 这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他

                            使用反射机制的代码所读取和使用}

      @Documented :注解表明这个注解应该被 javadoc工具记录

      @Target :注解使用的范围 : method ,parameter...

demo:

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;


@Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface isLogin {

}

注:在需要校验用户登入信息的接口上,controlle的方法上添加自定义的注解。

sept2 HandlerInterceptorAdapter 拦截器的实现



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


public class LoginInterceptor extends HandlerInterceptorAdapter {
//继承HandlerInterceptorAdapter 重写preHandler方法


/**
* This implementation always returns {@code true}.
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// handlerMethod封装方法定义相关的信息,如类,方法,参数等
HandlerMethod handlerMethod = (HandlerMethod) handler;
// 获取方法上的注解
isLogin isLogin = handlerMethod.getMethodAnnotation(isLogin.class);
// 没有islogin的注解就不判断
if (isLogin == null) {
return true;
}
else {
// TO DO : 判断session中是否有的用户信息(返回true后者false)
}
return true;
}
}

xml配置:

   

    <mvc:interceptors>
        <bean class="mystudy.base.LoggedinInterceptor" />
    </mvc:interceptors>

    <mybatis:scan base-package="mapper" template-ref="sqlSession"/>

     <bean id="handlerMapping" 

class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />


        

猜你喜欢

转载自blog.csdn.net/weixin_37794901/article/details/79834004