1.SpringBoot拦截器是什么

SpringBoot拦截器和过滤器是Spring Boot的一种机制,用于对请求和响应进行操作的拦截,是AOP编程的一种体现。该方法可以在不改变代码基本业务和逻辑的前提下对SpringBoot的一些操作进行拦截、过滤和更改。

SpirngBoot拦截器(Interceptor)和过滤器(Filter)的操作的如下图所示。如果不愿意仔细理解,也可以记住这个执行步骤就可以:过滤器(Filter)——>拦截器(Interceptor)——>ControllerAdavice——>Controller。

2.AOP编程

SpringBoot是AOP编程的思想体现。AOP编程即面向切面编程,是函数式编程的一种思想体现。AOP编程和OOP编程没有冲突。OOP编程的思路是封装、继承和多态,而AOP编程的思路是不改变原有接口和功能的基础上提供功能扩展。

一般来说,AOP编程的实现思路是提供代理,把一些常用功能如权限检查、日志、事务等,从每个业务方法中剥离出来,而提供代理统一实现。

SpringBoot拦截器、过滤器就是AOP编程的体现,即把部分功能统一剥离起来进行统一拦截、过滤和实现。

3.请求拦截和返回拦截

可以对请求和返回进行统一拦截。

一般来说,如果是非常简单的操作,可以用ControllerAdavice进行拦截。代码如下:

@ControllerAdvicepublic class TestResponseBodyAdvice implements ResponseBodyAdvice {@Overridepublic boolean supports(MethodParameter returnType, Class converterType) {Class targetClass = returnType.getMethod().getDeclaringClass();return true;}@Overridepublic Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {//操作return body;}}

如果是更复杂的操作,可以用拦截器(Interceptor)进行拦截,代码如下:

@Componentpublic class TokenInterceptor implements HandlerInterceptor {/** * 在访问Controller某个方法之前这个方法会被调用。 * * @param request * @param response * @param handler * @return false则表示不执行postHandle方法, true 表示执行postHandle方法 * @throws Exception */@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//false则表示不执行postHandle方法,不执行下一步chain链,直接返回responseif(/***相关操作***/) {return false;} else {return true;}}}

该方法的要点是:

1)可以自己选择preHandel和psotHanle操作;

2)此拦截器需要在Bean里进行注册;

注册代码(Configuration注入下)如下:

@AutowiredTokenInterceptor tokenInterceptor;/** * 添加拦截器 * @param registry */@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(tokenInterceptor).addPathPatterns("/api/**")//指定该类拦截的url.excludePathPatterns( "/static/**");//过滤静态资源}

2)如果有对request操作,会造成java.io.IOException: Stream closed问题;

4.Java.io.IOException: Stream closed问题解决

Java.io.IOException: Stream closed出现的原因是HTTP的Stream只允许操作一次,如果操作多次就会失败。

该问题的解决思路是:提供一个复制流,让操作基于复制流。

解决代码如下(原有拦截器保持不变):

1)提供文件解析:

public class HttpHelper {public static String getBodyString(HttpServletRequest request) throws IOException {StringBuilder sb = new StringBuilder();InputStream inputStream = null;BufferedReader reader = null;try {inputStream = request.getInputStream();reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));String line = "";while ((line = reader.readLine()) != null) {sb.append(line);}} catch (IOException e) {e.printStackTrace();} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}return sb.toString();}}

2)提供Filter过滤:

public class HttpServletRequestReplacedFilter implements Filter {@Overridepublic void destroy() {}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {ServletRequest requestWrapper = null;if(request instanceof HttpServletRequest) {requestWrapper = new RequestReaderHttpServletRequestWrapper((HttpServletRequest) request);}//获取请求中的流如何,将取出来的字符串,再次转换成流,然后把它放入到新request对象中。// 在chain.doFiler方法中传递新的request对象if(requestWrapper == null) {chain.doFilter(request, response);} else {chain.doFilter(requestWrapper, response);}}@Overridepublic void init(FilterConfig arg0) throws ServletException {}}

3)对请求的装饰,用于建立复制流。

public class RequestReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {private final byte[] body;public RequestReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {super(request);body = HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8"));}@Overridepublic BufferedReader getReader() throws IOException {return new BufferedReader(new InputStreamReader(getInputStream()));}@Overridepublic ServletInputStream getInputStream() throws IOException {final ByteArrayInputStream bais = new ByteArrayInputStream(body);return new ServletInputStream() {@Overridepublic int read() throws IOException {return bais.read();}@Overridepublic boolean isFinished() {return false;}@Overridepublic boolean isReady() {return false;}@Overridepublic void setReadListener(ReadListener readListener) {}};}}

4)在Bean操作(Configuration注入)中加入相关操作:

@Beanpublic FilterRegistrationBean httpServletRequestReplacedRegistration() {FilterRegistrationBean registration = new FilterRegistrationBean();registration.setFilter(new HttpServletRequestReplacedFilter());registration.addUrlPatterns("/*");registration.addInitParameter("paramName", "paramValue");registration.setName("httpServletRequestReplacedFilter");registration.setOrder(1);return registration;}

这个问题解决方案,最关键的部分其实是HttpServletRequestReplacedFilter里的

if(requestWrapper == null) {chain.doFilter(request, response);} else {chain.doFilter(requestWrapper, response);}

这是让复制流起作用的操作,从而避免流被关闭。