【问题标题】:Add namespace prefix in every element in SOAP response在 SOAP 响应中的每个元素中添加命名空间前缀
【发布时间】:2019-04-11 16:35:48
【问题描述】:

我正在创建一个 Web 服务,其中调用我的服务的客户端在 SOAP 响应的每个元素中都需要命名空间前缀。

在简单的例子中,客户想要这样的响应:

<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
   <soapenv:Body>
      <dlwmin:GetEmployeesByDeptResponse xmlns:dlwmin="http://tempuri.org/" 
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
         <dlwmin:EmployeesListResult>
            <dlwmin:Employee>
               <dlwmin:firstName>John</dlwmin:firstName>
               <dlwmin:lastName>Doe</dlwmin:lastName>
            </dlwmin:Employee>
            <dlwmin:Employee>
               <dlwmin:firstName>Audrey</dlwmin:firstName>
               <dlwmin:lastName>Gibson</dlwmin:lastName>
            </dlwmin:Employee>
         </dlwmin:EmployeesListResult>
      </dlwmin:GetEmployeesByDeptResponse>
   </soapenv:Body>
</soapenv:Envelope>

但我目前的反应是:

<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
   <soapenv:Body>
      <dlwmin:GetEmployeesByDeptResponse xmlns:dlwmin="http://tempuri.org/" 
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
         <EmployeesListResult>
            <Employee>
               <firstName>John</firstName>
               <lastName>Doe</lastName>
            </Employee>
            <Employee>
               <firstName>Audrey</firstName>
               <lastName>Gibson</lastName>
            </Employee>
         </EmployeesListResult>
      </dlwmin:GetEmployeesByDeptResponse>
   </soapenv:Body>
</soapenv:Envelope>

我的 SOAP 服务 (JAX-WS) 部署在 WebSphere Application Server 9.0 Network Deployment (FixPack 5) 上,源代码如下所示:

项目结构

EmployeesSearch.java

package com.pp.endpoints;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.xml.ws.BindingType;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;

import com.pp.entities.Employee;
import com.pp.entities.Employees;

@WebService(targetNamespace = "http://tempuri.org/", name = "EmployeesSearch", 
            portName = "EmployeesSearchPort", serviceName = "EmployeesSearchService", 
            wsdlLocation = "WEB-INF/wsdl/EmployeesSearchService.wsdl")
@SOAPBinding(style = Style.DOCUMENT)
@BindingType(javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)
public class EmployeesSearch {

    @WebMethod(operationName = "GetEmployeesByDeparetment", action = "GetEmployeesByDeparetment")
    @WebResult(name = "EmployeesListResult")
    @RequestWrapper(localName = "GetEmployeesByDeptRequest", className = "GetEmployeesByDeptRequest")
    @ResponseWrapper(localName = "GetEmployeesByDeptResponse", className = "GetEmployeesByDeptResponse")
    public Employees getEmployeesByDeparetment(@WebParam(name = "department") String department) {

        Employees employess = new Employees();

        if (department.equals("dev")) {
            Employee emp1 = new Employee("John", "Doe");
            employess.getEmpList().add(emp1);

            Employee emp2 = new Employee("Audrey", "Gibson");
            employess.getEmpList().add(emp2);
        } else if(department.equals("QA")) {
            Employee emp1 = new Employee("Sylvia", "Vinson");
            employess.getEmpList().add(emp1);

            Employee emp2 = new Employee("Zelenia", "Stark");
            employess.getEmpList().add(emp2);
        }

        return employess;
    }
}

GetEmployeesByDeptRequest.java

package com.pp.endpoints;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "department" })
@XmlRootElement(name = "GetEmployeesByDeptRequest")
public class GetEmployeesByDeptRequest implements Serializable {

    private static final long serialVersionUID = -6866935846016764952L;

    protected String department;

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

}

GetEmployeesByDeptResponse.java

package com.pp.endpoints;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import com.pp.entities.Employee;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "employeesListResult" })
@XmlRootElement(name = "GetEmployeesByDeptResponse")
public class GetEmployeesByDeptResponse implements Serializable {

    private static final long serialVersionUID = -3929452574007113319L;

    @XmlElement(name = "EmployeesListResult")
    protected Employee employeesListResult;

    public Employee getEmployeesListResult() {
        return employeesListResult;
    }

    public void setEmployeesListResult(Employee employeesListResult) {
        this.employeesListResult = employeesListResult;
    }
}

package-info.java

@javax.xml.bind.annotation.XmlSchema(namespace = "http://tempuri.org/", 
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.pp.endpoints;

Employee.java

package com.pp.entities;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Employee", propOrder = { "firstName", "lastName" })
public class Employee implements Serializable {

    private static final long serialVersionUID = -1382336004216274895L;

    @XmlElement(name = "firstName")
    protected String firstName;

    @XmlElement(name = "lastName")
    protected String lastName;

    public Employee(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

Employees.java

package com.pp.entities;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Employees", propOrder = { "empList" })
public class Employees implements Serializable {

    private static final long serialVersionUID = -6738577250797101596L;

    @XmlElement(name = "Employee", nillable = true)
    protected List<Employee> empList = new ArrayList<>();

    public Employees() { }

    public List<Employee> getEmpList() {
        if (empList == null) {
            empList = new ArrayList<Employee>();
        }

        return empList;
    }

    public void setEmpList(List<Employee> empList) {
        this.empList = empList;
    }
}

问题:为了在每个元素都有命名空间前缀的情况下获得响应,我应该在源代码中进行哪些更改。

【问题讨论】:

    标签: java soap jax-ws websphere-9


    【解决方案1】:

    请使用 HeaderHandler 类并添加这个 this.addToHeader(envelope, header, "dlwmin", "your endpoint");

     List<Handler> handlerChain = new ArrayList<Handler>();
              HeaderHandler hh = new HeaderHandler();
              handlerChain.add(hh);
              return handlerChain;
    

    例如:HeaderHandler

    public class HeaderHandler implements SOAPHandler<SOAPMessageContext> {
    
    
        public boolean handleMessage(SOAPMessageContext smc)throws Fault {
    
    
    
    
    
    
            Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    
    
            if (outboundProperty.booleanValue()) {
    
    
                SOAPMessage message = smc.getMessage();
    
    
    
                try {
    
                    if(App.sid!=null){
    
                                   message.setProperty("sid", App.sid);
    
                    }
    
                    SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope();               
    
                    SOAPHeader header = envelope.addHeader();
    
    
    
                    this.addToHeader(envelope, header, "To", "https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc");
    
    
    
                    if(App.jakiNaglowek==1){
    
                                    this.addToHeader(envelope, header, "Action", "http://CIS/BIR/PUBL/2014/07/IUslugaBIRzewnPubl/Zaloguj");
    
    
    
                    }
    
                    if(App.jakiNaglowek==2){
    
                    this.addToHeader(envelope, header, "Action", "http://CIS/BIR/PUBL/2014/07/IUslugaBIRzewnPubl/Wyloguj");
    
    
    
                   }
    
                    if(App.jakiNaglowek==3){
    
                                    this.addToHeader(envelope, header, "Action", "http://CIS/BIR/2014/07/IUslugaBIR/SetValue");
    
    
    
                      }
    
                    if(App.jakiNaglowek==4){
    
                                    this.addToHeader(envelope, header, "Action", "http://CIS/BIR/2014/07/IUslugaBIR/GetValue");
    
    
    
                     }
    
                    if(App.jakiNaglowek==5){
    
                                    this.addToHeader(envelope, header, "Action", "http://CIS/BIR/PUBL/2014/07/IUslugaBIRzewnPubl/DaneKomunikat");
    
    
    
                    }
    
    
    
                                   if(App.jakiNaglowek==7){
    
                                    this.addToHeader(envelope, header, "Action", "http://CIS/BIR/PUBL/2014/07/IUslugaBIRzewnPubl/DanePobierzPelnyRaport");
    
    
    
                       }
    
                    if(App.jakiNaglowek==6){
    
                    this.addToHeader(envelope, header, "Action", "http://CIS/BIR/2014/07/IUslugaBIR/PobierzCaptcha");
    
    
    
    
    
                   }
    
    //                if(App.jakiNaglowek==7){
    
    //                            this.addToHeader(envelope, header, "Action", "http://CIS/BIR/PUBL/2014/07/IUslugaBIRzewnPubl/DaneKomunikat");
    
    //               
    
    //                           //
    
    //                }
    
    
    
                    if(App.jakiNaglowek==9){
    
                                    this.addToHeader(envelope, header, "Action", "http://CIS/BIR/2014/07/IUslugaBIR/SprawdzCaptcha");
    
    
    
    
    
                      }
    
                    if(App.jakiNaglowek==10){
    
                                    this.addToHeader(envelope, header, "Action", "http://CIS/BIR/PUBL/2014/07/IUslugaBIRzewnPubl/DaneSzukaj");
    
    
    
    
    
                     }
    
                   //  Header headTo = new Header(new QName("http://www.w3.org/2005/08/addressing", "To", "wsa"), wsaTo, new JAXBDataBinding(String.class));
    
    
    
    
    
    
    
                   // SOAPElement security =
    
                        //    header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
    
    
                    //SOAPElement usernameToken =
    
                     //       security.addChildElement("UsernameToken", "wsse");
    
                   // usernameToken.addAttribute(new QName("xmlns:wsu"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
    
    
                  //  SOAPElement username =
    
                   //         usernameToken.addChildElement("Username", "wsse");
    
                   // username.addTextNode("");
    
    
                  //  SOAPElement password =
    
                   //         usernameToken.addChildElement("Password", "wsse");
    
                  //  password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
    
                  //  password.addTextNode("");
    
    
                    //Print out the outbound SOAP message to System.out
    
                    message.writeTo(System.out);
    
                    System.out.println("");
    
    
    
                } catch (Exception e) {
    
                    e.printStackTrace();
    
                }
    
    
            } else {
    
                try {
    
    
    
                    //This handler does nothing with the response from the Web Service so
    
                    //we just print out the SOAP message.
    
                    SOAPMessage message = smc.getMessage();
    
    
    
                    message.writeTo(System.out);
    
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    
                    message.writeTo(stream);
    
                    String response = new String(stream.toByteArray(), "utf-8");
    
    
    
                    System.out.println("");
    
                    //System.out.println("Dodatkowy wydruk");
    
                   // System.out.println("Dziwne "+response);
    
                   // System.out.println("KONIEC");
    
    
    
    
    
                } catch (Exception ex) {
    
                    ex.printStackTrace();
    
                }
    
            }
    
    
    
    
            return outboundProperty;
    
    
        }
    
    
        public Set getHeaders() {
    
                    Set<QName> set = new HashSet<QName>();
    
            // Make sure the '[{http://www.w3.org/2005/08/addressing}]Action' header
    
            // is handled in case the device set the 'MustUnderstand' attribute to '1'
    
            set.add(new QName("http://www.w3.org/2005/08/addressing", "Action"));
    
            return set;
    
        }
    
    
        public boolean handleFault(SOAPMessageContext context) {
    
            //throw new UnsupportedOperationException("Not supported yet.");
    
                    System.out.println("Inside handle fault:: " + context);
    
    
    
            return true;
    
        }
    
    
        public void close(MessageContext context) {
    
        //throw new UnsupportedOperationException("Not supported yet.");
    
        }
    
    
    
        private void addToHeader(SOAPEnvelope envelope, SOAPHeader header, String key, String value) throws SOAPException {
    
            Name qname = envelope.createName(key, "wsa", "http://www.w3.org/2005/08/addressing");
    
            SOAPHeaderElement element = header.addHeaderElement(qname);
    
            element.addTextNode(value);
    
    
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多