java后端cors跨域设置白名单
时间: 2023-12-15 21:03:26 浏览: 222
关于Ajax跨域问题及解决方案详析
Java后端cors跨域设置白名单可以通过以下步骤实现:
1. 在web.xml文件中添加CorsFilter过滤器。
2. 在CorsFilter过滤器中设置允许跨域的域名白名单,可以使用通配符*表示允许所有域名跨域访问。
3. 在CorsFilter过滤器中设置允许跨域的请求方法,例如GET、POST等。
4. 在CorsFilter过滤器中设置允许跨域的请求头,例如Content-Type、Authorization等。
5. 在CorsFilter过滤器中设置允许跨域的响应头,例如Access-Control-Allow-Origin、Access-Control-Allow-Methods等。
具体实现可以参考以下代码:
```
public class CorsFilter implements Filter {
private String allowOrigin;
private String allowMethods;
private String allowCredentials;
private String allowHeaders;
private String exposeHeaders;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
allowOrigin = filterConfig.getInitParameter("allowOrigin");
allowMethods = filterConfig.getInitParameter("allowMethods");
allowCredentials = filterConfig.getInitParameter("allowCredentials");
allowHeaders = filterConfig.getInitParameter("allowHeaders");
exposeHeaders = filterConfig.getInitParameter("exposeHeaders");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
if (StringUtils.isNotBlank(allowOrigin)) {
response.setHeader("Access-Control-Allow-Origin", allowOrigin);
}
if (StringUtils.isNotBlank(allowMethods)) {
response.setHeader("Access-Control-Allow-Methods", allowMethods);
}
if (StringUtils.isNotBlank(allowCredentials)) {
response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
}
if (StringUtils.isNotBlank(allowHeaders)) {
response.setHeader("Access-Control-Allow-Headers", allowHeaders);
}
if (StringUtils.isNotBlank(exposeHeaders)) {
response.setHeader("Access-Control-Expose-Headers", exposeHeaders);
}
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
```
阅读全文