CORS(跨域资源共享)是一种安全机制,允许Web应用程序在不同的域之间进行资源共享。在Java RESTful API中,我们可以使用过滤器(Filter)来实现CORS支持。
以下是一个简单的示例,展示了如何在Java RESTful API中使用CORS过滤器:
CORSFilter.java
的文件,并实现javax.servlet.Filter
接口:import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
@WebFilter(asyncSupported = true, urlPatterns = { "/*" })
public class CORSFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
httpResponse.setHeader("Access-Control-Max-Age", "3600");
httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
Access-Control-Allow-Origin
: 允许所有域名访问。你可以根据需要将其更改为特定的域名。Access-Control-Allow-Methods
: 允许的HTTP方法,例如GET、POST、PUT和DELETE。Access-Control-Max-Age
: 预检请求(preflight request)的缓存时间。Access-Control-Allow-Headers
: 允许的自定义请求头。现在,你的Java RESTful API应该已经支持CORS。客户端可以从不同的域名访问你的API,而无需担心跨域问题。