How to enable CORS on server-side code in java
Solution 1:
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)
@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() {
}
}
Solution 2:
For a JavaEE 7 App you need to register this class in the ResourceConfig by adding following class to your war.
@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 {
...
}
Solution 3:
In Jersey, I use the ResourceConfig class to register the CORSFilter. Like ,
import org.glassfish.jersey.jackson.JacksonFeature;
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,
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.service.JerseyApplication</param-value>
</init-param>