做项目的时候我们常遇到的问题就是执行对应的逻辑代码前完成数据验证,sprint boot 如何实现的呢?
拦截器
过滤器
对于以上两个概念的区别可以自行查找网上的资料
现在我们一步步实现拦截器
1 创建spring boot 项目
2 创建拦截器
package com.interceptor; 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; @Component public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { response.sendRedirect("/v1/banner"); System.out.println("拦截器生效"); return true; // true 继续执行,false 直接返回 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
以上我们创建了拦截器并加入到了组件中
package com; import com.interceptor.LoginInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; @SpringBootConfiguration public class InterceptorConfig extends WebMvcConfigurationSupport { @Autowired LoginInterceptor loginInterceptor; @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns("/v1/banner"); } }
完成拦截器的注册,创建rest请求体验拦截器