本篇内容主要讲解“如何在spring boot中添加拦截器”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何在spring boot中添加拦截器”吧!
如何在spring boot中添加拦截器?
1.首先自己实现一个拦截器
import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class MyInterceptor implements HandlerInterceptor{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandler"); return true;//这里一定要返回true要不然后面的不会执行 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandler"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterHandler"); }}
2.实现WebMvcConfigurer接口并重写addInterceptors方法
@Configurationpublic class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor()).addPathPatterns("/**");//将自己的拦截器注册到spring中并添加拦截的路径 } @Bean MyInterceptor myInterceptor(){ return new MyInterceptor();//提供自己的拦截器的bean }}
3.创建controller进行测试
@RestControllerpublic class HelloController { @GetMapping("gethello") public String getHello(){ System.out.println("get hello"); return "get hello"; }}
到此,相信大家对“如何在spring boot中添加拦截器”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。