zoukankan      html  css  js  c++  java
  • 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);
    

    如果我们将这一行注释起来的话,那么在浏览器上就不会看到结果了。

  • 相关阅读:
    代码仓库
    介绍
    创建mysql数据库的命令
    操作流程
    Ubuntu20.04下Mercurial的安装与配置
    邮件列表-OpenJDK
    代码约定--OpenJDK
    ubuntu20.04 下 ADB调试android工具的安装
    openjdk开发者指南
    verifying module: xxx: initializing sumdb.Client: reading tree note: malformed note 解决方案
  • 原文地址:https://www.cnblogs.com/zifeiy/p/9911056.html
Copyright © 2011-2022 走看看