一、入门
客户端发起请求进入DispatcherServlet,再进入我们自定义的拦截器,拦截器实现的是HandlerIntercepter接口,如果拦截成功,就向客服端返回拦截器响应信息;
如果验证通过,就进入对应的controller,然后结果一系列操作,返回controller响应信息
(二)、 SpringMVC拦截器配置及类初始化
在dispatcher-servlet.xml文件设置mvc拦截器
<mvc:interceptors> <!-- 定义在这里,所有的都会拦截--> <!-- <bean></bean>--> <mvc:interceptor> <!----> <mvc:mapping path="/manage/**"/> <!--指定拦截器初始化类--> <bean class="com.mmall.controller.common.interceptor.AuthorityInterceptor"/> </mvc:interceptor> </mvc:interceptors>
创建拦截器初始化类AuthorityInterceptor
package com.mmall.controller.common.interceptor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; import java.util.Iterator; import java.util.Map; // 拦截器初始化类 @Slf4j public class AuthorityInterceptor implements HandlerInterceptor { // controller处理之前 @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { log.info("preHandle"); // 请求中Controller中的方法名 HandlerMethod handlerMethod = (HandlerMethod) o; // 解析handlerMethod String methodName = handlerMethod.getMethod().getName(); String className = handlerMethod.getBean().getClass().getSimpleName(); //解析参数,具体的参数key以及value是什么,我们打印日志 StringBuffer requestParamBuffer = new StringBuffer(); Map paramMap = httpServletRequest.getParameterMap(); Iterator it = paramMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String mapKey = (String) entry.getKey(); String mapValue = StringUtils.EMPTY; // httpServletRequest这个参数的map,里面的value返回的是一个String[] Object obj = entry.getValue(); if (obj instanceof String[]) { String[] strs = (String[])obj; mapValue = Arrays.toString(strs); } requestParamBuffer.append(mapKey).append("=").append(mapValue); } // 还没有写完 return true; } // controller 处理之后 @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { log.info("postHandle"); } // 所有处理完成后调用 @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { log.info("afterCompletion"); } }