Spring Boot使用過濾器Filter
阿新 • • 發佈:2018-11-05
首先建立一個測試用的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);
如果我們將這一行註釋起來的話,那麼在瀏覽器上就不會看到結果了。