springboot拦截器
先创建一个Interceptor类实现HandlerInterceptor接口
package ax.tst.interceptor; import ax.f4j.controller.BaseController; import ax.tst.common.AuthTools; import ax.tst.model.RequestLog; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.stereotype.Component; 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.Date; /** * 请求拦截器 * * @author QQQ * @since 2018年5月15日14:51:06 */ @Component public class RequestInterecptor extends BaseController implements HandlerInterceptor { @Autowired private MongoOperations mongoOperations; @Autowired private AuthTools authTools; @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { // 记录接口请求日志 RequestLog requestLog = new RequestLog(authTools.getUserInfo().getId(), getRemoteAddress(), httpServletRequest.getServletPath(), new Date()); mongoOperations.save(requestLog); return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
注册
package ax.tst; import ax.tst.interceptor.RequestInterecptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class TstApiConfig extends WebMvcConfigurerAdapter { @Autowired private RequestInterecptor requestInterecptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(requestInterecptor).addPathPatterns("/**"); super.addInterceptors(registry); } }