java基于spring boot简单实现filter功能
一、新建spring boot项目,编写测试Controller。
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class MyController {
@PostMapping("/test")
public String test(int id,String name){
log.info("过滤器测试 controller");
return "success";
}
}
二、编写过滤器实现类。
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* 注解配置filter有两种方式:方式1 通过@Componet或@Configuration,这种方式会过滤所有url
* 方式二:通过@WebFilter(urlPatterns={"/test"})配置,这种方式可以指定url,但是需要在启动类上加@ServletComponentScan注解
*/
@WebFilter(urlPatterns = "/**")
@Slf4j
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
log.info("filter init");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
log.info("id:"+request.getParameter("id"));
log.info("name:"+request.getParameter("name"));
//json 格式 通过流的方式接收
ServletInputStream inputStream = request.getInputStream();
byte[] b = new byte[1024];
StringBuilder sb = new StringBuilder();
while (inputStream.available()>0) {
inputStream.read(b, 0, 1024);
sb.append(new String(b));
}
log.info("json:"+sb.toString());
//允许请求通行
chain.doFilter(request,response);
}
@Override
public void destroy() {
System.out.println("filter destroy");
}
}
启动spring boot项目,配置没问题会执行init方法。
2018-11-26 15:10:20.568 INFO 38120 --- [ost-startStop-1] com.web.filter.MyFilter : filter init
三、利用apizz调用接口,观察日志。
2018-11-26 15:18:37.844 INFO 38120 --- [nio-8080-exec-3] com.web.filter.MyFilter : id:123
2018-11-26 15:18:37.844 INFO 38120 --- [nio-8080-exec-3] com.web.filter.MyFilter : name:ding
2018-11-26 15:18:37.844 INFO 38120 --- [nio-8080-exec-3] com.web.filter.MyFilter : json:{
"param1": "abc",
"param2": "def"
}
2018-11-26 15:18:37.845 INFO 38120 --- [nio-8080-exec-3] com.web.controller.MyController : 拦截器测试 controller