1.在SpringMVC.xml中添加配置:
<!-- 自定义拦截器(映射到Controller中的方法级别)-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer" ref="webBindingInitializer"></property>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="interceptors">
<list>
<bean class="com.lys.power.intercept.MethodsInterceptor" />
<bean class="org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor">
<constructor-arg ref="conversionService"/>
</bean>
</list>
</property>
</bean>
2.创建MethodsInterceptor 方法拦截器:
public class MethodsInterceptor extends HandlerInterceptorAdapter {
@SuppressWarnings("unchecked")
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod handler2=(HandlerMethod) handler;
if(handler2!=null){
StringBuffer s=new StringBuffer("本次准备访问方法的绝对路劲:");
s.append(handler2.getBeanType().getName()+" ");//访问的类路径
Method method=handler2.getMethod();
s.append( Modifier.toString(method.getModifiers())+" " + method.getReturnType().getSimpleName() + " " + method.getName() + "(");
for (Class<?> param : method.getParameterTypes()) {
s.append(param.getSimpleName()).append(",");
}
if(method.getParameterTypes().length>0){
s.deleteCharAt(s.length() - 1).append(")");
}else{
s.append(")");
}
Log.in.info(s.toString());
}
/**
* 在Controller方法执行后进行拦截
*/
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if(modelAndView!=null){
Log.in.info("跳转页面:WEB-INF/jsp/"+modelAndView.getViewName()+".jsp");
}
}
/**
* 在DispatcherServlet完全处理完请求后被调用,可以在该方法中进行一些资源清理的操作???
*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
Log.in.info("【执行action方法完毕】");
}
}
- 编写一个Controller测试