How to handle CORS using JAX-RS with Jersey

后端 未结 5 686
北荒
北荒 2020-11-22 02:01

I\'m developing a java script client application, in server-side I need to handle CORS, all the services I had written in JAX-RS with JERSEY. My code:

@Cross         


        
5条回答
  •  自闭症患者
    2020-11-22 02:27

    peeskillet's answer is correct. But I get this error when refresh the web page (it is working only on first load):

    The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://127.0.0.1:8080' is therefore not allowed access.
    

    So instead of using add method to add headers for response, I using put method. This is my class

    public class MCORSFilter implements ContainerResponseFilter {
        public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
        public static final String ACCESS_CONTROL_ALLOW_ORIGIN_VALUE = "*";
    
        private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
        private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE = "true";
    
        public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
        public static final String ACCESS_CONTROL_ALLOW_HEADERS_VALUE = "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, Accept";
    
        public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
        public static final String ACCESS_CONTROL_ALLOW_METHODS_VALUE = "GET, POST, PUT, DELETE, OPTIONS, HEAD";
    
        public static final String[] ALL_HEADERs = {
                ACCESS_CONTROL_ALLOW_ORIGIN,
                ACCESS_CONTROL_ALLOW_CREDENTIALS,
                ACCESS_CONTROL_ALLOW_HEADERS,
                ACCESS_CONTROL_ALLOW_METHODS
        };
        public static final String[] ALL_HEADER_VALUEs = {
                ACCESS_CONTROL_ALLOW_ORIGIN_VALUE,
                ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE,
                ACCESS_CONTROL_ALLOW_HEADERS_VALUE,
                ACCESS_CONTROL_ALLOW_METHODS_VALUE
        };
        @Override
        public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
            for (int i = 0; i < ALL_HEADERs.length; i++) {
                ArrayList value = new ArrayList<>();
                value.add(ALL_HEADER_VALUEs[i]);
                response.getHttpHeaders().put(ALL_HEADERs[i], value); //using put method
            }
            return response;
        }
    }
    
    
    

    And add this class to init-param in web.xml

    
                com.sun.jersey.spi.container.ContainerResponseFilters
                com.yourpackage.MCORSFilter
            
    

    提交回复
    热议问题