spring自定義注解攔截器的配置


1.創建注解文件 (文件格式為注解) 這里面什么都不需要寫 文件名就是注解名稱 如下 是@anno

package com.ABC123.anno;

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

/**
 * 自定義注解. 在方法上添加這個注解. 必須登錄之后才能執行這個方法
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface anno {

}

  2.創建一個類先實現HandlerInterceptor接口里面的方法 當然不想要全部都實現可以繼承他的適配器HandlerInterceptorAdapter類

package com.ABC123.inter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ABC123.anno.anno;
import com.ABC123.utils.UserContext;

public class LoginInter extends HandlerInterceptorAdapter {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	//之前攔截
	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Exception {
		//你請求的目標必須是方法
		if(obj instanceof HandlerMethod) {
			
			HandlerMethod hm = (HandlerMethod) obj;
		Object o = 	hm.getMethodAnnotation(anno.class);
		if(o==null) {//沒有這個注解
			return true;
			
		}else {//有注解
			
			if(UserContext.getCurrent() == null) {//沒有登錄
				
				resp.sendRedirect("/paike/login.jsp");
				return false;
			}else { //登錄了
				return true;
			}
			
		}
		
		}
		
		
		return true;
	}

}

  3.最后配置springmvc的xml文件

<!-- 開啟mvc -->  
	<mvc:annotation-driven />
	<bean id="inter" class="com.ABC123.inter.LoginInter"></bean>
	
	<!-- 攔截器配置 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/**"/><!-- 攔截所有 -->
			<ref bean="inter"/>
		</mvc:interceptor>
	</mvc:interceptors>

  4.在需要攔截的類上面寫生注解@anno

當進入這個已經有注解的方法時會先經過攔截 符合的才放行

 


免責聲明!

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



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