在 Spring Boot 中使用 Filters 实现请求过滤和预处理
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class SimpleCORSFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
@Override
public void init(FilterConfig filterConfig) {
// 初始化代码,如果有必要的话
}
@Override
public void destroy() {
// 销毁代码,如果有必要的话
}
}
这段代码定义了一个简单的跨域资源共享(CORS)Filter,用于处理HTTP请求并设置适当的CORS头部。在实际的应用中,你可能需要根据具体需求调整这些头部的值。这个Filter被标记为@Component
,Spring Boot会自动将其加入到Filter链中。
评论已关闭