java的 自定义注解拦截器

自定义的拦截器,是看了别人的文章,做的精简,所以算是转载

在项目中,右键,创建@ interface 这就是注解,在注解上加上 两个注解 ,对这个注解进行限定

@Target(value=ElementType.METHOD)//定义了只能用于方法上
@Retention (RetentionPolicy.RUNTIME) //定义了这个拦截器存在于项目运行时
public @interface RequiredLogin {

	
}
然后创建一个拦截器,继承HandlerInter 

Logininterceptor implements HandlerInterceptor 
对preHandle 进行重写 ,因为它是在执行方法之前,对请求 进行拦截

@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if(handler instanceof HandlerMethod){
			HandlerMethod handlerMethod=(HandlerMethod)handler;
			//用来获取  RequiredLogin注解
			RequiredLogin requiredLogin = handlerMethod.getMethodAnnotation(RequiredLogin.class);
			if(requiredLogin !=null && UserContext.getCurrent()== null){
				response.sendRedirect("/p2p-web/login.html");
				return false;
			}
		}
		return true ;
	}

最后在springmvc 中 对拦截器 进行配置

<mvc:interceptors>
 	       <mvc:interceptor>
 	          <mvc:mapping path="/**"/>
 	          <bean  class="cn.zzsxt.p2p.util.Logininterceptor"></bean>
 	        </mvc:interceptor>
 </mvc:interceptors>
 	
如果想起作用,就需要在进行校验的方法上,加上自己定义的注释,进行了

@RequiredLogin
	@RequestMapping("/list")
	public String cha(Model model){
		   

我定义的是,如果方法上有 我定义的注释,但是上下文中没有内容  ,就会回到 登录界面。

更多功能,参考出处



 出处 : https://my.oschina.net/whhos/blog/679384









猜你喜欢

转载自blog.csdn.net/qq_39387571/article/details/78754779