首先,先创建一个实现Filter的过滤器ResponseFilter
@Component
public class ResponseFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
// 这里需要重写ResponseWrapper,因为原方法是没有获取返回值的功能
ResponseWrapper wrapperResponse = new ResponseWrapper((HttpServletResponse) response);
// 这里只拦截返回,直接让请求过去,如果在请求前有处理,可以在这里处理
filterChain.doFilter(request, wrapperResponse);
byte[] content = wrapperResponse.getContent();//获取返回值
// 判断是否有值
if (content.length > 0) {
// 这里是返回的内容
String str = new String(content, "UTF-8");
System.out.println("拦截的返回值:" + str);
String strChange = null;
try {
strChange="拦截到你啦!";
} catch (Exception e) {
e.printStackTrace();
}
//把返回值输出到客户端
response.setContentLength(strChange.length());
ServletOutputStream out = response.getOutputStream();
out.write(strChange.getBytes());
out.flush();
}
}
}
因为原方法是没有获取返回值的功能,所以需要重写ResponseWrapper
类
public class ResponseWrapper extends HttpServletResponseWrapper {
private ByteArrayOutputStream buffer;
private ServletOutputStream out;
public ResponseWrapper(HttpServletResponse httpServletResponse) {
super(httpServletResponse);
buffer = new ByteArrayOutputStream();
out = new WrapperOutputStream(buffer);
}
@Override
public ServletOutputStream getOutputStream()
throws IOException {
return out;
}
@Override
public void flushBuffer()
throws IOException {
if (out != null) {
out.flush();
}
}
public byte[] getContent()
throws IOException {
flushBuffer();
return buffer.toByteArray();
}
class WrapperOutputStream extends ServletOutputStream {
private ByteArrayOutputStream bos;
public WrapperOutputStream(ByteArrayOutputStream bos) {
this.bos = bos;
}
@Override
public void write(int b)
throws IOException {
bos.write(b);
}
@Override
public boolean isReady() {
// TODO Auto-generated method stub
return false;
}
@Override
public void setWriteListener(WriteListener arg0) {
// TODO Auto-generated method stub
}
}
}
现在只需要让这个过滤器生效即可:
@SpringBootApplication
public class SpringbootFilterApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootFilterApplication.class, args);
}
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new ResponseFilter());
// 过滤的地址
registration.addUrlPatterns("/filterTest");
return registration;
}
}
测试的controller:
@RestController
public class testController {
@GetMapping("/filterTest")
public String filterTest() {
return "没有拦截到我!";
}
}