SpringBoot(二):Web之Filter

一、添加Filter、Listen、Serlvet兩方式

  • 代碼註冊經過ServletRegistrationBean、 FilterRegistrationBean 和 ServletListenerRegistrationBean 得到控制。 
    也能夠經過實現 ServletContextInitializer 接口直接註冊。代碼式實例

 

  • 在 SpringBootApplication 上使用@ServletComponentScan 註解後,Servlet、Filter、Listener 能夠直接經過 @WebServlet、@WebFilter、@WebListener 註解自動註冊,無需其餘代碼。

二、註解實現方式

  • MyFilter.java
@WebFilter(servletNames="myFilter",urlPatterns = "/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest) {
            System.out.println(MessageFormat.format("請求路徑url=>{0}", ((HttpServletRequest) servletRequest).getRequestURI()));
        }
        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {

    }
}
  • QuickStartApplication.java
@ServletComponentScan
@SpringBootApplication
public class QuickStartApplication {

	public static void main(String[] args) {
		SpringApplication.run(QuickStartApplication.class, args);
	}
}

   

http://localhost:8080/getUser.do,後臺日誌輸出html

請求路徑url=>/getUser.do
name=>小王
 java

相關文章
相關標籤/搜索