SpringBoot拦截器
- 新建一个拦截器CommonInterceptor,继承HandlerInterceptorAdapter。给大家说一下,在继承HandlerInterceptorAdapter有三个拦截器是经常使用的:
1.preHandle在业务处理器处理请求之前被调用
2.postHandle在业务处理器处理请求执行完成后,生成视图之前执行
3.afterCompletion在DispatcherServlet完全处理完请求后被调用
@Component
@Slf4j
public class CommonInterceptor implements HandlerInterceptor {
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
log.info("请求ip:"+request.getRemoteAddr());
log.info("请求的方法:"+request.getMethod());
ModelMap modelMap = modelAndView.getModelMap();
modelMap.addAttribute("titlename","德云社");
}
}
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Autowired
CommonInterceptor commonInterceptor;
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/");
super.addResourceHandlers(registry);
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(commonInterceptor);
}
}
@Api(value = "test", description = "测试样例文档")
@Controller
@RequestMapping("/test")
@Slf4j
@Validated
public class InterceptorTest {
@ApiOperation(value = "拦截器测试", httpMethod = "GET")
@GetMapping("interceptortest")
public String index(Model model){
model.addAttribute("content","hi , 郭德纲 !");
return "interceptortest";
}
}