SpringBoot拦截器和过滤器是Spring Boot的一种机制,用于对请求和响应进行操作的拦截,是AOP编程的一种体现。该方法可以在不改变代码基本业务和逻辑的前提下对SpringBoot的一些操作进行拦截、过滤和更改。
SpirngBoot拦截器(Interceptor)和过滤器(Filter)的操作的如下图所示。如果不愿意仔细理解,也可以记住这个执行步骤就可以:过滤器(Filter)——>拦截器(Interceptor)——>Controller Adavice——>Controller。
2.AOP编程
SpringBoot是AOP编程的思想体现。AOP编程即面向切面编程,是函数式编程的一种思想体现。AOP编程和OOP编程没有冲突。OOP编程的思路是封装、继承和多态,而AOP编程的思路是不改变原有接口和功能的基础上提供功能扩展。
一般来说,AOP编程的实现思路是提供代理,把一些常用功能如权限检查、日志、事务等,从每个业务方法中剥离出来,而提供代理统一实现。
SpringBoot拦截器、过滤器就是AOP编程的体现,即把部分功能统一剥离起来进行统一拦截、过滤和实现。
3.请求拦截和返回拦截
一般来说,如果是非常简单的操作,可以用Controller Adavice进行拦截。代码如下:
@ControllerAdvice
public class TestResponseBodyAdvice implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
Class targetClass = returnType.getMethod().getDeclaringClass();
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
//操作
return body;
}
}
如果是更复杂的操作,可以用拦截器(Interceptor)进行拦截,代码如下:
@Component
public class TokenInterceptor implements HandlerInterceptor {
/**
* 在访问Controller某个方法之前这个方法会被调用。
*
* @param request
* @param response
* @param handler
* @return false则表示不执行postHandle方法, true 表示执行postHandle方法
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//false则表示不执行postHandle方法,不执行下一步chain链,直接返回response
if(/***相关操作***/) {
return false;
} else {
return true;
}
}
}
该方法的要点是:
1)可以自己选择preHandel和psotHanle操作;
@Autowired
TokenInterceptor tokenInterceptor;
/**
* 添加拦截器
* @param registry
*/
@Override
public 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只允许操作一次,如果操作多次就会失败。
解决代码如下(原有拦截器保持不变):
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 {
@Override
public void destroy() {
}
@Override
public 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);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
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"));
}
@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 int read() throws IOException {
return bais.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
}
4)在Bean操作(Configuration注入)中加入相关操作:
@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;
}
这个问题解决方案,最关键的部分其实是 HttpServletRequestReplacedFilter里的
if(requestWrapper == null) {
chain.doFilter(request, response);
} else {
chain.doFilter(requestWrapper, response);
}
原文地址:https://blog.csdn.net/wangzhezhilu001/article/details/130828540
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_44236.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!