Spring 注解攔截器使用詳解


Spring mvc攔截器

平時用到的攔截器通常都是xml的配置方式。今天就特地研究了一下注解方式的攔截器。

配置Spring環境這里就不做詳細介紹。本文主要介紹在Spring下,基於注解方式的攔截器。

第一步:定義Interceptor 實現類

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{                
                //在這里實現自己的權限驗證邏輯,判斷使用session中是否有username,有的話,則驗證通過,不攔截。
                String username = (String) request.getSession().getAttribute("username");
                if(username != null )//如果驗證成功返回true
                    return true;
                else//如果驗證失敗
                {
                    //返回到登錄界面
                    response.sendRedirect(request.getContextPath()+"/account/login");
                    return false;
                }       
            }
        }
        else
            return true;   
     }
}

第二步:自定義Annotation實現類,添加於具體某個需要攔截的Controller。

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

第三步:把定義的攔截器加到Spring MVC的攔截體系中。

(1):在SpringMVC的配置文件添加攔截器所需要的schema,

  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc.xsd" >

(2):添加完schema后,便可以在springMVC的配置文件中直接使用標簽:<mvc:interceptors>進行聲明攔截器。攔截器聲明配置文件代碼如下:

<mvc:interceptors> 
        <!-- 如果不定義 mvc:mapping path 將攔截所有的URL請求 -->
        <bean class="com.demo.web.auth.AuthInterceptor"></bean>
</mvc:interceptors>  

第四步:在Controller的方法中添加自定義攔截注解。只需要在具體的方法中添加@AuthPassport皆可

    @AuthPassport
    @RequestMapping(value={"/index","/hello"})
    public ModelAndView index(){
        
        ModelAndView modelAndView = new ModelAndView();  
        modelAndView.addObject("message", "Hello World!");  
        modelAndView.setViewName("index");  
        return modelAndView;
    }        

通過上面的四步,便可以實現基於注解的方式對url進行攔截。

 代碼下載地址:http://pan.baidu.com/s/1sjp5B1z


免責聲明!

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



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