Spring Boot使用过滤器Filter
首先创建一个测试用的controller:TestController:
package com.zifeiy.test.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@RequestMapping("/test")
public String test() {
return "zifeiy test";
}
}
然后运行主程序,在浏览器访问http://localhost:8080/test
,可以看到
zifeiy test
的结果。
然后新建一个filter:
package com.zifeiy.test.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
@WebFilter(filterName = "testUserFilter", urlPatterns = "/*")
public class TestUserFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
System.out.println("zifeiy: filter init ...");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("zifeiy: filter ...");
chain.doFilter(request, response);
}
@Override
public void destroy() {
Filter.super.destroy();
System.out.println("zifeiy: filter destroy ...");
}
}
并且在如程序中加上一行@ServletComponentScan
,完整的主程序:
TestApplication.java:
package com.zifeiy.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
再次运行主程序,在浏览器访问http://localhost:8080/test
,
可以看到命令行中出现了:
zifeiy: filter ...
但是还是能够在浏览器中看到
zifeiy test
的结果。
后来才发现原来是因为以下这行的原因:
chain.doFilter(request, response);
如果我们将这一行注释起来的话,那么在浏览器上就不会看到结果了。