SpringMVC 注解实现权限拦截

1.新建一个注解类

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthPassport {
    boolean validate() default true;
}


2.在需要验证权限的Controller上添加注解

@AuthPassport

@AuthPassport(validate=false)//validate默认为true,表示需要验证,当validate 为false时表示不需要验证


3.新建一个拦截器

public class AuthInterceptor extends HandlerInterceptorAdapter {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
            AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);
            if(authPassport == null || authPassport.validate() == false)
                return true;
            else{
                   //拦截代码,通过验证则返回true,否则返回false
            }
        }
        else
            return true;   
     }


4.在配置中设置拦截器

 <mvc:interceptors>  
        <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />  
        <!-- 如果不定义 mvc:mapping path 将拦截所有的URL请求 -->
        <bean class="包名.AuthInterceptor"></bean>
    </mvc:interceptors>

猜你喜欢

转载自blog.csdn.net/torrytang/article/details/49470713