java 设置Access-Control-Allow-Origin
时间: 2023-08-17 09:12:34 浏览: 104
在 Java 中,要设置 `Access-Control-Allow-Origin` 头部字段允许跨域请求,可以通过使用 Servlet 过滤器来实现。以下是一个示例代码:
```java
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 初始化操作
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// 设置允许跨域的域名,可以使用 * 表示允许所有域名访问
response.setHeader("Access-Control-Allow-Origin", "*");
// 设置允许的请求方法
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
// 设置允许的请求头部字段
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// 继续处理请求
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
// 销毁操作
}
}
```
然后,在你的 web.xml 文件中配置过滤器:
```xml
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>com.example.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
这样就可以在 Java 中设置 `Access-Control-Allow-Origin` 头部字段,从而允许跨域请求。
阅读全文