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

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 拦截器的实现

拦截器判断controller的函数上,是否配置自定义的登入拦截注解,有则进行是否登入的校验

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>

     <bean id="handlerMapping" 

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

 

        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值