您的位置:首页 > 产品设计 > UI/UE

java中,自定义注解拦截器来实现,在需要的拦截的方法上面加上一个注解@AccessRequired

2017-11-24 15:31 711 查看
java中,自定义注解拦截器来实现,在需要的拦截的方法上面加上一个注解@AccessRequired

spring mvc Controller中的使用实例

[java]
view plain
copy

/** 
     * 注解拦截器方法 
     * @return 
     */  
    @RequestMapping(value="/urlinter",method=RequestMethod.GET)  
    @AccessRequired  
    public @ResponseBody String urlInterceptorTest() {  
        return "通过拦截器:user"+request.getAttribute("currUser");  
    }  

如何实现以上实例呢?

定义一个注解:

[java]
view plain
copy

import java.lang.annotation.ElementType;  
import java.lang.annotation.RetentionPolicy;  
import java.lang.annotation.Target;  
import java.lang.annotation.Retention;  
  
@Target(ElementType.METHOD)  
@Retention(RetentionPolicy.RUNTIME)  
public @interface AccessRequired {  
      
}  

搞一个拦截器:

[java]
view plain
copy

/** 
 * 拦截url中的access_token 
 * @author Nob 
 *  
 */  
public class UserAccessApiInterceptor extends HandlerInterceptorAdapter {  
  
    public boolean preHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler) throws Exception {  
  
        HandlerMethod handlerMethod = (HandlerMethod) handler;  
        Method method = handlerMethod.getMethod();  
        AccessRequired annotation = method.getAnnotation(AccessRequired.class);  
        if (annotation != null) {  
           System.out.println("你遇到了:@AccessRequired");  
           String accessToken = request.getParameter("access_token");  
            /** 
             * Do something 
             */  
            response.getWriter().write("没有通过拦截,accessToken的值为:" + accessToken);  
        }  
        // 没有注解通过拦截  
        return true;  
    }  
}  

在spring mvc配置文件中:

[java]
view plain
copy

<!-- 拦截器 -->  
    <mvc:interceptors>  
        <mvc:interceptor>  
            <!-- 对所有的请求拦截使用/** ,对某个模块下的请求拦截使用:/myPath/* -->  
            <mvc:mapping path="/api/**" />  
            <ref bean="userAccessInterceptor" />  
        </mvc:interceptor>  
    </mvc:interceptors>  
  
    <bean id="userAccessInterceptor"  
        class="com.banmacoffee.web.interceptor.UserAccessApiInterceptor">  
    </bean>  

注意问题:

    如果你使用了<mvc:resources mapping="/resources/**" location="/resources/" />来配置静态资源,那么配置如上拦截器的时候就要使用使用了全局拦截/**,否则会拦截静态资源抛出ResourceHttpRequestHandler cannot be cast to HandlerMethod异常

办法一:加上拦截路径前缀

[java]
view plain
copy

<mvc:mapping path="/path/**" />  

<!-- 这里使用一个path前置,如api,否则会拦截静态资源 -->

办法二:在自定义拦截器中使用instanceof 过滤ResourceHttpRequestHandler 类型

大功告成,你可以在拦截器里为所欲为,并且把它加载任何你想的Controller 请求的方法上
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐