How to enable CORS on server side of JAX-WS in jav

2019-06-02 06:02发布

问题:

I have exposed SOAP webservice using JAX-WS in java. Following is the code snippet:

package com.soap.calculator;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public class Calci {

  @WebMethod    
  public int add(int x, int y){
      return x+y;
  }

  @WebMethod    
  public int subtract(int x, int y){
      return x-y;
  }

}

Following is code snippet for publishing this webservice:

package com.soap.calculator;

import javax.xml.ws.Endpoint;

public class Server {
 public static void main(String agrs[]){
     Endpoint ep = Endpoint.publish("http://localhost:8081/SoapwebService", new Calci());
     System.out.println("Service created");
 }
}

I am using jQuery plugin for communicating with this webservice using SOAP.Since this webservice is exposed on some other domain, browser is enabled in CORS mode and generating preflight request for accessing web service. My question is How to enable CORS support on server side using jax-ws?

回答1:

As JAX-RS, response should be enriched with CORS headers. In JAX-RS implementation that is achieved by Filter definition. In JAX-WS, you can apply the same technique with "Handlers".

https://docs.oracle.com/cd/E13222_01/wls/docs103/webserv_adv/handlers.html

Here you can find an example. Use SOAPHandler and test if it is an "OutBoundMessage", then add CORS headers here.