zoukankan      html  css  js  c++  java
  • springboot 添加 Filter过滤

    通过注解方式完成

    1. 编写一个Filter类:
    package com.test.filters;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @WebFilter(urlPatterns = "/*", filterName = "ResponseFilter")
    public class ResponseFilter implements Filter {
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
    
            HttpServletRequest reqs = (HttpServletRequest) servletRequest;
    
            // response.setHeader("Access-Control-Allow-Origin",reqs.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Origin","*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
    
    

    注解 @WebFilter(urlPatterns = "/*", filterName = "ResponseFilter") 表示/*所有请求都走这个filter,这个filter。

    1. 在springboot的启动类加一个扫描注解: @ServletComponentScan("com.test.filters") // 过滤器,基于注解方式
    package com.test;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.ServletComponentScan;
    
    @SpringBootApplication
    @ServletComponentScan("com.test.filters") // 过滤器,基于注解方式
    public class TourismApplication {
    	public static void main(String[] args) {
    		SpringApplication.run(TourismApplication.class, args);
    	}
    
    }
    
    

    大功告成

  • 相关阅读:
    《Python for Beginners》学习笔记(2)
    《Python for Beginners》学习笔记(6)
    《Python for Beginners》学习笔记(4)
    《C Primer Plus》阅读笔记(1)
    《Python for Beginners》学习笔记(7)暨结课总结
    《Python for Beginners》学习笔记(5)
    《Python基础教程》读书笔记(1)
    《Python for Beginners》学习笔记(3)
    让Rails版的FCKEditor支持动态设置上传目录
    FCKEditor与rails的集成
  • 原文地址:https://www.cnblogs.com/wangleiblog/p/12819885.html
Copyright © 2011-2022 走看看