Spring boot使用拦截器

在springboot web开发中经常需要拦截器,创建拦截器的步骤:

实现HandlerInterceptor接口,重写接口中的三个方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InterceptorConfig implements HandlerInterceptor {

private static final Logger logger = LoggerFactory.getLogger(InterceptorConfig.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

logger.info("------->在controller执行之前执行<-------");

return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

logger.info("------->在controller执行之后,页面渲染之前执行<-------");
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
logger.info("------->页面渲染之后,多用于资源清理操作<-------");
}
}

注册拦截器

1
2
3
4
5
6
7
8
9
10
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

public class WebAppConfig extends WebMvcConfigurerAdapter {

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new InterceptorConfig()).addPathPatterns("/*");
}
}
-------------本文结束感谢您的阅读-------------