在springboot中,如何使用拦截器?
实现拦截器
public class InterceptorDemo extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
StringBuffer requestURL = httpServletRequest.getRequestURL();
System.out.println("前置拦截器1 preHandle: 请求的uri为:"+requestURL.toString());
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("拦截器1 postHandle: ");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("拦截器1 afterCompletion: ");
}
}
注册拦截器
@Configuration
public class InterceptorConfig implements WebMvcConfigurer{
//注册自定义拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new InterceptorDemo2()).addPathPatterns("/**");
registry.addInterceptor(new InterceptorDemo()).addPathPatterns("/**");
}
}
在springboot中,如何扩展springmvc的功能
在springboot中,提供了很多springMVC的自动配置,但是这些自动配置还不满足我们的开发需求,所以我们可以在默认的配置上进行扩展。
@Configuration <-----注解
public class WebMVCConfig implements WebMvcConfigurer { <----实现WebMvcConfigurer
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
registry.addViewController("/index").setViewName("index");
//定义跳转到主页面的视图
registry.addViewController("/dashboard.html").setViewName("dashboard");
}
}