1. 程式人生 > >spring-interceptor-01

spring-interceptor-01

配置

    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 針對於那個路勁下的內容進行攔截,這個路勁同資原始檔的定位符  -->
            <mvc:mapping path="/pages/**/*.action"/> 
            <bean class="cn.mldn.interceptor.MyInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors
>

實現

package cn.mldn.interceptor;

import java.lang.reflect.Method;

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

import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("[*** preHandle ] cls = " + handler.getClass());
// 1 必須轉型為HandlerMethod類的物件之後才可以知道操作的是那個Action,是那個具體的操作方法 HandlerMethod handlerMethod = (HandlerMethod) handler ; // 2、拼湊讀取資原始檔中key的內容 String validatorKey = handlerMethod.getBeanType().getSimpleName()+"."+handlerMethod.getMethod().getName()+".rules"; // 3、取得Action類中對應的getMsgSource()方法 Method msgSourceMethod = handlerMethod.getBean().getClass().getMethod("getSourceMessage",String.class); // 4、取得具體的驗證規則 String validateContent = (String) msgSourceMethod.invoke(handlerMethod.getBean(),validatorKey); if(validateContent == null || "".equals(validateContent)) { return true ; } else { } //5、針對於每一個具體的操作進行驗證處理 String rules [] = validateContent.split("\\|"); //實現資料的拆分處理操作 // 5、取得所有的提交引數 MethodParameter mp [] = handlerMethod.getMethodParameters() ; for (int x = 0 ; x < mp.length ; x ++) { System.out.println(mp[x].getMethod() + "," + mp[x].getParameterName() + "," + mp[x].getParameterType()); } System.out.println(" validateContent = " + validateContent); System.out.println("[*** preHandle] bean = " + handlerMethod.getBean().getClass()); System.out.println("[*** preHandle] beanType = " + handlerMethod.getBeanType()); System.out.println("[*** preHandle] method = " + handlerMethod.getMethod()); return true; //如果不返回true表示截停,不在執行後續的控制層操作 } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("[*** afterCompletion ] cls = " + handler.getClass()); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("[*** postHandle ] cls = " + handler.getClass()); } }