JAVA && Spring && SpringBoot2.x — 学习目录
1. 拦截器的基本使用
1.1 拦截器的实现类
- 实现Spring的HandlerInterceptor接口;
- 继承实现HandlerInterceptor接口的类,例如:HandlerInterceptorAdapter;
1.2 HandlerInterceptor方法介绍
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception;
void postHandle(
HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception;
void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception;
- preHandler:业务处理器处理请求之前被调用,对用户的request进行处理,若返回值为true,则继续调用后续的拦截器和目标方法;若返回值为false,则终止请求;这里可以加上登录校验,权限拦截等。
- postHandler:Controller执行后但未返回视图前调用该方法,这里可以对返回用户前的模型数据进行加工处理。
- afterCompletion:Controller执行后且返回视图后调用,可以得到Controller时的异常信息,这里可以记录操作日志,资源清理等。
1.3 将拦截器加入到MVC中
在SpringBoot 2.0以上, WebMvcConfigurerAdapter已过时,但是WebMvcConfigurerAdapter实际上是WebMvcConfigurer接口的空实现类。故有两种方法可以实现:
推荐使用:implements WebMvcConfigurer
1. @EnableWebMvc + implements WebMvcConfigurer
在扩展类中重写父类的方法即可,这种方法会屏蔽springboot对SpringMVC的自动配置。
2. implements WebMvcConfigurer
在扩展类中重写父类的方法即可,这种方法会使用springboot对SpringMVC的自动配置。
3. extends WebMvcConfigurationSupport
在扩展类中重写父类的方法即可,这种方法会屏蔽springboot对SpringMVC的自动配置。
根据官方文档,尽量不要使用@EnableWebMvc注解,因为他会关闭自动配置。
详情请了解——SpringBoot中对SpringMVC的自动配置
@Component
public class LogInterceptor implements HandlerInterceptor {
private final static Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
//业务处理器处理请求之前被调用,对用户的request进行处理
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info("【拦截器】-【已进入拦截器!!】");
return true;
}
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Autowired
private LogInterceptor logInterceptor;
//配置拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//指定拦截器,指定拦截路径
registry.addInterceptor(logInterceptor).addPathPatterns("/**");
}
}
2. 拦截器的自定义注解
创建注解类。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD}) ////作用于类、接口等与方法上
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyLimit {
int intVal() default 5;
String stringVal() default "";
}
创建拦截器类-AnnotationInterceptor
@Component
public class AnnotationInterceptor implements HandlerInterceptor {
private final static Logger logger = LoggerFactory.getLogger(AnnotationInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//判断当前被拦截的方法是否含有注解
boolean assignableFromMethod = handler.getClass().isAssignableFrom(HandlerMethod.class);//[额赛额包] 指定的
logger.info("当前方法上是否有注解" + assignableFromMethod);
if (assignableFromMethod) {
//获取当前方法的自定义注解拦截器的注解
MyLimit methodAnnotation = ((HandlerMethod) handler).getMethodAnnotation(MyLimit.class);
logger.info("当前方法的注解:" + methodAnnotation);
if (methodAnnotation == null) {
return true;
}
//获取注解上的参数
int intVal = methodAnnotation.intVal();
String stringVal = methodAnnotation.stringVal();
logger.info("打印注解上的参数:[intVal={}][stringVal={}]", intVal, stringVal);
}
return true;
}
}
配置拦截器
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Autowired
private LogInterceptor logInterceptor;
@Resource
private AnnotationInterceptor annotationInterceptor;
//配置拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//指定拦截器,指定拦截路径
registry.addInterceptor(logInterceptor).addPathPatterns("/**");
registry.addInterceptor(annotationInterceptor);
}
}
使用注解
@RequestMapping(value = "/get", method = RequestMethod.GET)
@ResponseBody
@MyLimit(stringVal = "哈哈,哈哈哈")
public String getUesr(@RequestParam(value = "str", required = false) Integer integer) {
try {
if (integer == 2) {
throw new RuntimeException("请求地址不合法");
}
}catch (Exception e){
logger.error("请求参数不合法",e);
}
logger.info("请求参数:str={}",integer);
SysQuartzJobConfig sysQuartzJobConfig = sysQuartzJobConfigMapper.selectByPrimaryKey(integer);
return JSON.toJSONString(sysQuartzJobConfig);
}
效果:
MyPrefix 16591 INFO com.Interceptor.impl.AnnotationInterceptor - 当前方法上是否有注解true
MyPrefix 16591 INFO com.Interceptor.impl.AnnotationInterceptor - 当前方法的注解:@com.Interceptor.annotation.MyLimit(intVal=5, stringVal=哈哈,哈哈哈)
MyPrefix 16592 INFO com.Interceptor.impl.AnnotationInterceptor - 打印注解上的参数:[intVal=5][stringVal=哈哈,哈哈哈]
3. 获取请求参数解决java.io.IOException: Stream closed
在拦截器中通过request.getInputStream();获取body中的信息后,此时在Controller中使用@RequestBody注解获取参数出现异常。
流关闭异常出现原因分析
- 输入流中含有一个“隐式指针”记录当前流读取的位置,故一旦我们在拦截器中将读取InputStream,那么后续无法使用@RequestBody注解。
- 可以在【拦截器】之前使用【过滤器】,包装request请求,重写getInputStream()方法;
- 将数据保存到内存Byte[]中,使用ByteArrayInputStream进行操作。
引入依赖
在springboot中,无需引入。
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>8.5.15</version>
</dependency>
新建拦截器
@Component
public class LogInterceptor implements HandlerInterceptor {
private final static Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
//业务处理器处理请求之前被调用,对用户的request进行处理
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info("【拦截器】-【已进入拦截器!!】");
logger.info("【拦截器】-request的类型{}", request.getClass());
String bodyString = HttpHelper.getBodyString(request);
logger.info("bodyString的值:" + bodyString);
return true;
}
}
新建过滤器
public class HttpServletRequestReplacedFilter implements Filter {
private final static Logger logger = LoggerFactory.getLogger(HttpServletRequestReplacedFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
logger.info("【过滤器】-【已进入过滤器!】");
ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
chain.doFilter(requestWrapper, response);
}
@Override
public void destroy() {
}
}
包装request
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final static Logger logger = LoggerFactory.getLogger(BodyReaderHttpServletRequestWrapper.class);
private final byte[] body;
public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
//获取到请求体
logger.info("【过滤器】-【获取请求的body信息】");
body = HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8"));
}
//重写方法
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
//节点流
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener listener) {
//监听
logger.info("【拦截器】-【BodyReaderHttpServletRequestWrapper ReadListener:{}】", this);
}
@Override
public int read() throws IOException {
return bais.read();
}
};
}
}
读取Body的工具类
public class HttpHelper {
private final static Logger logger = LoggerFactory.getLogger(HttpHelper.class);
public static String getBodyString(HttpServletRequest request) {
StringBuffer sb = new StringBuffer();
InputStream inputStream;
BufferedReader bufferedReader;
try {
//将数据保存到数组中,每次读取的时候,都读取一遍
inputStream = request.getInputStream();
//将字节数组当做输出的目的地
//字节流转换为字符流(处理流)
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
logger.error("数据读取异常", e);
}
return sb.toString();
}
}
拦截器过滤器加入到容器中
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Autowired
private LogInterceptor logInterceptor;
// @Resource
// private AnnotationInterceptor annotationInterceptor;
//配置拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//指定拦截器,指定拦截路径
registry.addInterceptor(logInterceptor).addPathPatterns("/**");
// registry.addInterceptor(annotationInterceptor);
}
@Bean
public FilterRegistrationBean httpServletRequestReplacedRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new HttpServletRequestReplacedFilter());
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("httpServletRequestReplacedFilter");
registration.setOrder(1);
return registration;
}
}
执行日志
2019-07-02 16:40:07,598 INFO [22059] [http-nio-8080-exec-1] [] (DirectJDKLog.java:173): Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-07-02 16:40:07,598 INFO [22059] [http-nio-8080-exec-1] [] (FrameworkServlet.java:524): Initializing Servlet 'dispatcherServlet'
2019-07-02 16:40:07,610 INFO [22071] [http-nio-8080-exec-1] [] (FrameworkServlet.java:546): Completed initialization in 12 ms
2019-07-02 16:40:07,620 INFO [22081] [http-nio-8080-exec-1] [] (HttpServletRequestReplacedFilter.java:22): 【过滤器】-【已进入过滤器!】
2019-07-02 16:40:07,623 INFO [22084] [http-nio-8080-exec-1] [] (BodyReaderHttpServletRequestWrapper.java:26): 【过滤器】-【获取请求的body信息】
2019-07-02 16:40:07,636 INFO [22097] [http-nio-8080-exec-1] [] (LogInterceptor.java:24): 【拦截器】-【已进入拦截器!!】
2019-07-02 16:40:07,636 INFO [22097] [http-nio-8080-exec-1] [] (LogInterceptor.java:25): 【拦截器】-request的类型class com.filter.BodyReaderHttpServletRequestWrapper
2019-07-02 16:40:07,638 INFO [22099] [http-nio-8080-exec-1] [] (LogInterceptor.java:27): bodyString的值:{"age":"12","name":"liming"}
2019-07-02 16:40:07,797 INFO [22258] [http-nio-8080-exec-1] [] (UserController.java:41): 请求参数:str={"age":"12","name":"liming"}