码迷,mamicode.com
首页 > 编程语言 > 详细

springboot 添加 Filter过滤

时间:2020-05-02 23:07:25      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:with   port   eth   frame   work   pattern   web   headers   res   

通过注解方式完成

  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);
	}

}

大功告成

springboot 添加 Filter过滤

标签:with   port   eth   frame   work   pattern   web   headers   res   

原文地址:https://www.cnblogs.com/wangleiblog/p/12819885.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!