首页 > 解决方案 > 定制肥皂响应

问题描述

我正在使用 Apache CXF 开发 Web 服务项目。我不想处理异常并自定义响应:

public class FaultInterceptor extends
AbstractSoapInterceptor {

public FaultInterceptor() {
    super(Phase.MARSHAL);
}
public void handleMessage(SoapMessage soapMessage) throws Fault {
Fault fault = (Fault) soapMessage.getContent(Exception.class);
QName faultCode = new QName("11111");
fault.setFaultCode(faultCode);

所以这是我在回复中得到的:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
  <soap:Fault>
     <faultcode>soap:11111</faultcode>
     <faultstring>Message</faultstring>
  </soap:Fault>
 </soap:Body>

我怎样才能删除文本“肥皂:”,只让 11111?

请帮助我,并在此先感谢

标签: javasoapcxf

解决方案


自从迁移旧系统以使其行为完全相同以来,我一直在寻找完全相同的东西。

我想出了以下解决方案。

class SoapFaultEndpointInterceptor extends EndpointInterceptorAdapter
{
    private static final Pattern SOAP_CODE_FAULT_SPLITTER = Pattern.compile(":");


    @Override
    public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception
    {
        SaajSoapMessage soapResponse = (SaajSoapMessage) messageContext.getResponse();
        modifySoapFaultCode(soapResponse);

        return super.handleFault(messageContext, endpoint);
    }

    private void modifySoapFaultCode(SaajSoapMessage soapResponse)
    {
        try {
            SOAPMessage soapMessage = soapResponse.getSaajMessage();
            SOAPBody body = soapMessage.getSOAPBody();
            SOAPFault soapFault = body.getFault();

            modifyFaultCodeIfPresent(soapFault);
        } catch (SOAPException e) {
            throw new SoapModifiyingException("Modifying faultcode did not work properly.", e);
        }
    }

    private void modifyFaultCodeIfPresent(SOAPFault fault)
    {
        if (fault != null) {
            String newFaultCode = cleanFaultCode(fault.getFaultCode());
            fault.setFaultCode(newFaultCode);
        }
    }

    private String cleanFaultCode(String oldFaultCode)
    {
        String[] cleanFaultCode = SOAP_CODE_FAULT_SPLITTER.split(oldFaultCode);
        Assert.isTrue(cleanFaultCode.length == 2, "No proper faultcode provided!");

        return cleanFaultCode[1].trim();
    }

通过添加SoapFaultEndpointInterceptor到您的拦截器,它应该可以工作。

@EnableWs
@Configuration
public class SoapServerConfig extends WsConfigurerAdapter
{
    @Override
    public void addInterceptors(List<EndpointInterceptor> interceptors)
    {
        interceptors.add(new SoapFaultEndpointInterceptor());
    }
}

推荐阅读