過濾器解決檔案上傳下載跨域問題

微笑的花發表於2020-10-20
@Component
@ConfigurationProperties(prefix = "keyconfig")	
public class CorsFilter implements Filter {

    //上傳路徑
    private String devHeader;
    
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {  
        HttpServletResponse response = (HttpServletResponse) res;  
        devHeader=devHeader.replace("'", "");
        response.setHeader("Access-Control-Allow-Credentials","true");
        response.setHeader("Access-Control-Allow-Origin",devHeader);
        //response.setHeader("Access-Control-Allow-Headers","Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
        response.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Headers, Authorization");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");  
        response.setHeader("Access-Control-Max-Age", "3600");  
        chain.doFilter(req, res);  
    }  
    public void init(FilterConfig filterConfig) {}  
    public void destroy() {}
    
    
	public String getDevHeader() {
		return devHeader;
	}
	public void setDevHeader(String devHeader) {
		this.devHeader = devHeader;
	}  
}

其中一下程式碼用於從yml獲取值,注意要有get/set
(在aplication.yml中有keyconfig.devHeader=‘*’

@ConfigurationProperties(prefix = "keyconfig")
private String devHeader;
public String getDevHeader() {
		return devHeader;
	}
	public void setDevHeader(String devHeader) {
		this.devHeader = devHeader;
	}  

注意:如果專案中有JavaBean 來專門對映配置,在過濾器中@Autowired是獲取不到的
因為web應用啟動的順序是:listener->filter->servlet

如果希望可以用專門對映配置的JavaBean 來獲取yml中的值而不希望在過濾器中配置,可以通過在init方法中使用filterConfig引數或在dofilter方法中使用request引數來獲取

相關文章