springMvc基於注解登錄攔截器


先定義一個攔截器注解

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
    
}

在定義一個攔截器

/**
 * 登錄攔截器
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            LoginRequired loginRequired = findAnnotation((HandlerMethod) handler, LoginRequired.class);
            //沒有聲明需要權限,或者聲明不驗證權限
            if(loginRequired==null){
                return true;
            }else{
                String token=request.getHeader("token");
                if(StringUtils.isEmpty(token)){
                    token=request.getParameter("token");
                }
                //在這里實現自己的權限驗證邏輯
                if(!StringUtils.isEmpty(token)){//如果驗證成功返回true(這里直接寫false來模擬驗證失敗的處理)
                    return true;
                }else{//如果驗證失敗
                    response.getWriter().write("您還未登錄");
                    return false;
                }       
            }
        }else{
            return true;
        }
    }

    private <T extends Annotation> T findAnnotation(HandlerMethod handler, Class<T> annotationType) {
        T annotation = handler.getBeanType().getAnnotation(annotationType);
        if (annotation != null) return annotation;
        return handler.getMethodAnnotation(annotationType);
    }
}

spring配置

 
         

<!-- spring 3.1版本后才支持攔截方法名,需要引入一下配置 -->

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<mvc:annotation-driven />

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**" />
        <bean class="com.xxx.xxxx.LoginInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

 Controller層數直接使用

@ResponseBody
@RequestMapping(value="",method=RequestMethod.GET)
@LoginRequired
protected Map<String,Object> index(){
    return null;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM