如何使用SpringMVC攔截器的preHandle方法獲取當(dāng)前執(zhí)行的目標方法
如訪問http://localhost:8080/courses/testEncoding在攔截器中可以獲取到testEncoding方法
ps:可以使用HandlerMethod獲取到該方法,但是原本正常運行的程序會報錯:
java.lang.ClassCastException: org.springframework.web.servlet.resource.ResourceHttpRequestHandler cannot be cast to org.springframework.web.method.HandlerMethod
頁面可以顯示,但是并無CSS樣式。。刪除HandlerMethod語句就可以正常運行
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
???? System.out.println("執(zhí)行preHandle");
???? HandlerMethod hm = (HandlerMethod) arg2;
???? System.out.println("當(dāng)前執(zhí)行的對象是"+hm.getMethod());
???? return true;
}
2017-12-18
if (o instanceof HandlerMethod)?
強轉(zhuǎn)之前加個判斷
2017-08-19
自問自答。。
決定不鉆牛角尖了,直接使用request.getRequestURI()獲取到了。。。
附上代碼:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse arg1, Object arg2) throws Exception {
???? System.out.println("執(zhí)行preHandle");
???? System.out.println("getRequestURI"+request.getRequestURI());
???? return true;
}
以及SpringMVC配置文件中的攔截器配置
<!-- 攔截來自所有的請求 -->
<mvc:interceptors>
? ? <mvc:interceptor>
????? ? <mvc:mapping path="/**"/>
????? ? <mvc:exclude-mapping path="/**/fonts/*"/>
???? ????<mvc:exclude-mapping path="/**/*.css"/>
???? ????<mvc:exclude-mapping path="/**/*.js"/>
???? ????<mvc:exclude-mapping path="/**/*.png"/>
???? ????<mvc:exclude-mapping path="/**/*.gif"/>
???? ????<mvc:exclude-mapping path="/**/*.jpg"/>
???? ????<mvc:exclude-mapping path="/**/*.jpeg"/>
????? ? <bean class="com.springmvc.demo.interceptor.TestInterceptor" />
????</mvc:interceptor>
</mvc:interceptors>