package com.createdpro.api.config; import jakarta.servlet.*; import jakarta.servlet.annotation.WebFilter; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * 允许跨域请求 * @author createdpro */ @Component @WebFilter(urlPatterns = "/*", filterName = "myFilter") public class OriginFilter implements Filter { private static final List<String> allow = new ArrayList<>(); static { // 在这里配置可以通过跨域的客户端 host 地址 allow.add("http://localhost:8080"); allow.add("http://localhost:8081"); allow.add("https://createdpro.com"); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; if (allow.contains(request.getHeader("Origin"))){ response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "X-requested-with, content-type, Login-Token"); response.setHeader("Access-Control-Allow-Credentials", "true"); } chain.doFilter(req, res); } @Override public void destroy() { } }
spring boot 使用 Filter 配置后端允许跨域
创建时间: 6-6 9:47
浏览: 21
创建时间: 6-6 9:47
浏览: 21
*本文遵循 CC BY-NC-SA 许可协议。转载请注明出处!