java 如何在java中的服务器端代码上启用CORS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44905898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to enable CORS on server-side code in java
提问by Soumyajit Chatterjee
We are having a situation where UI is running on one host, and it is trying to communicate with the resources which are available on another host. The problem here is that, the UI is not be able to make call to the resources because that resource lives in a different domain and cross domain requests will not work unless the server is CORS enabled .
我们遇到的情况是 UI 在一台主机上运行,它试图与另一台主机上的可用资源进行通信。这里的问题是,UI 无法调用资源,因为该资源位于不同的域中,除非服务器启用 CORS,否则跨域请求将无法工作。
In-order to make server CORS enabled, We have done the below changes .
为了启用服务器 CORS,我们进行了以下更改。
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
@Provider
public class CORSFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException
{
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers","origin, content-type, accept, authorization");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
However I am not able to figure out where I need to map/configure this class,since there is no config files (web.xml). I don't have much knowledge on enabling CORS on server-side . Please suggest how to proceed further .
但是我无法弄清楚我需要在哪里映射/配置这个类,因为没有配置文件 (web.xml)。我对在服务器端启用 CORS 了解不多。请建议如何进一步进行。
回答by D. Peter
As far as I'm concerned the following are working
就我而言,以下是有效的
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS,HEAD");
Edit : (For spring cloud netflix and maybe others)
编辑:(对于 spring cloud netflix 和其他人)
@Component
public class HeadersFilter implements Filter {
@Override
public void init(FilterConfig fc) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain fc) throws IOException, ServletException {
if(servletResponse instanceof HttpServletResponse){
HttpServletResponse response = (HttpServletResponse) servletResponse;
// here add the headers
}
fc.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
回答by mszalbach
For a JavaEE 7 App you need to register this class in the ResourceConfig by adding following class to your war.
对于 JavaEE 7 应用程序,您需要通过将以下类添加到您的War中来在 ResourceConfig 中注册此类。
@ApplicationPath( "/" )
public class ApplicationConfig
extends ResourceConfig {
public ApplicationConfig() {
register( new CORSFilter() );
}
}
Maybe you also need to increase the priority of your Filter by adding the following class level annotation:
也许您还需要通过添加以下类级别注释来提高过滤器的优先级:
@Provider
@Priority( Priorities.HEADER_DECORATOR)
public class CORSFilter implements ContainerResponseFilter {
...
}
回答by Tanu
In Jersey, I use the ResourceConfig class to register the CORSFilter. Like ,
在 Jersey 中,我使用 ResourceConfig 类来注册 CORSFilter。喜欢 ,
import org.glassfish.jersey.Hymanson.HymansonFeature;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.server.ResourceConfig;
public class JerseyApplication extends ResourceConfig {
public JerseyApplication() {
register(CORSFilter.class);
}
}
`
`
and link this in web.xml like,
并将其链接到 web.xml 中,例如,
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.service.JerseyApplication</param-value>
</init-param>
回答by kubo44
There are 2 things you have to do:
你必须做两件事:
If your resource is password protected, you have to allow preflight OPTIONS requests to run through without credentials, in web.xml e.g.:
<security-constraint> <web-resource-collection> <web-resource-name>application</web-resource-name> <url-pattern>/*</url-pattern> <http-method-omission>OPTIONS</http-method-omission> </web-resource-collection> <auth-constraint> <role-name>user</role-name> </auth-constraint> </security-constraint>
Use servlet filter to take care of preflight OPTIONS requests. For maven add this dependency
<dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>cors-filter</artifactId> <version>2.6</version> </dependency>
add filter to web.xml:
<filter> <filter-name>CORS</filter-name> <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class> </filter> <filter-mapping> <filter-name>CORS</filter-name> <url-pattern>/rest/*</url-pattern> </filter-mapping>
如果您的资源受密码保护,您必须允许在没有凭据的情况下运行预检选项请求,例如在 web.xml 中:
<security-constraint> <web-resource-collection> <web-resource-name>application</web-resource-name> <url-pattern>/*</url-pattern> <http-method-omission>OPTIONS</http-method-omission> </web-resource-collection> <auth-constraint> <role-name>user</role-name> </auth-constraint> </security-constraint>
使用 servlet 过滤器处理预检选项请求。对于 maven 添加此依赖项
<dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>cors-filter</artifactId> <version>2.6</version> </dependency>
向 web.xml 添加过滤器:
<filter> <filter-name>CORS</filter-name> <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class> </filter> <filter-mapping> <filter-name>CORS</filter-name> <url-pattern>/rest/*</url-pattern> </filter-mapping>
回答by fujy
You have to enable it in your server first, check the website below to see how to configure your server (i.e., Tomcat) to enable CORS
您必须先在您的服务器中启用它,请查看以下网站以了解如何配置您的服务器(即 Tomcat)以启用 CORS