简体   繁体   中英

Create SOAP Attribute in JAXB

I am currently learning JAXB and Web Service and I have this problem that I dont know how to solve.

Suppose I have this very simple class that I annotated with JAXB.

@XmlRootElement
public class Customer {
    private int custID;
    private String custName;
    //getters and setters
}

And I have this class that I am exposing as a Web Service. (Note: I hardcode everything here for simplicity but this connects to DB)

@WebService
public class CustomerWS {

    @WebMethod(operationName = "customerData")
    public Customer getCustomer(){
      Customer cust = new Customer();
      cust.setCustID(12345);
      cust.setCustName("John Doe");     
      return cust;
    }
}

The SOAP envelope response is like this.

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:customerDataResponse xmlns:ns2="http://test.com/">
         <return>
            <custID>12345</custID>
            <custName>John Doe</custName>
         </return>
      </ns2:customerDataResponse>
   </S:Body>
</S:Envelope>

Now suppose I have another property in the customer entity called status and they wanted this property as attribute to the soap response to be like below instead of being part of the customer element. (A = Active, I = Inactive)

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:customerDataResponse status="A" xmlns:ns2="http://test.com/">
         <return>
            <custID>12345</custID>
            <custName>John Doe</custName>
         </return>
      </ns2:customerDataResponse>
   </S:Body>
</S:Envelope>

@XmlRootElement
public class Customer {
    private int custID;
    private String custName;

    //Another Annotation??? (A or I only)
    private String status;
    //getters and setters
}

How can I annotate my class to satisfy this requirement? Thanks

Everything annotated on the Customer class will be relative to the customer element.

This is because JAX-WS is responsible for forming the message envelope, and then JAXB marshals the body of the message into this envelope. When it comes time for JAXB to marshal the body it is too late to change the envelope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM