在 Spring Boot 中使用 Filter

Filter 是Web开发中的利器,可以非常方便的让我们切入功能功能到系统中去。本文演示如何在Spring Boot中定义,使用Filter。

本文中使用 Spring Boot 构建Rest服务实验手册(一) 中的案例进行演示。

新建一个Filter

新建一个名为: cn.com.hohistar.spbt.todoapi.config.filter 的包,在包中新建一个名为: PerfsFilter 的类,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Component
@Order(1)
public class PerfsFilter implements Filter {

private static final Logger LOG = LoggerFactory.getLogger(PerfsFilter.class);

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

long start = System.currentTimeMillis();

filterChain.doFilter(servletRequest, servletResponse);

long end = System.currentTimeMillis();

LOG.info("url {}, exection time is: {}ms", ((HttpServletRequest)servletRequest).getRequestURL().toString(), (end - start));
}
}

改变HTTP返回数据

获取返回数据

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class ResultWrapper extends HttpServletResponseWrapper {

private ByteArrayOutputStream buffer;

private ServletOutputStream out;

public ResultWrapper(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() {

return false;
}

@Override
public void setWriteListener(WriteListener arg0) {
}
}
}

添加统一格式

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
32
33
34
35
36
37
@Component
public class ResultFilter implements Filter {

private static final Logger LOG = LoggerFactory.getLogger(ResultFilter.class);

private static final String API_RESULT = "{\"succ\":true,\"code\":null,\"msg\":null,\"data\":";

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

LOG.info("Execute Fitler, start...");

ResultWrapper wrapper = new ResultWrapper((HttpServletResponse)servletResponse);

filterChain.doFilter(servletRequest, wrapper);
byte[] content = wrapper.getContent();

String str = "";
if (content.length > 0) {
str = new String(content, "UTF-8");
LOG.info("Retrun value: {}", str);
}

StringBuffer buf = new StringBuffer(API_RESULT);
buf.append(str);
buf.append("}");

ServletOutputStream out = servletResponse.getOutputStream();
out.write(buf.toString().getBytes());
out.flush();
out.close();


LOG.info("Execute Fitler, ...End");

}
}

注册Filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
public class FilterConfig {

@Bean
public FilterRegistrationBean<ResultFilter> regResultFilter(){
FilterRegistrationBean<ResultFilter> registrationBean
= new FilterRegistrationBean<>();

registrationBean.setFilter(new ResultFilter());
registrationBean.addUrlPatterns("/todo/*");

return registrationBean;
}
}

本文标题:在 Spring Boot 中使用 Filter

文章作者:晨星

发布时间:2019年12月15日 - 12:12

最后更新:2020年05月28日 - 16:05

原始链接:https://www.mls-tech.info/java/springboot-use-filter/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。