WebService CXF 解决 CDATA

阅读更多

Webservice 遇到特殊字符,请出CDATA

      本文前置要求:CXF3.0.1 Spring3.2 ,注解方式(其它方式类同),下面直接贴代码

 

@WebService
public interface IMPService {
....
}

 

 

 

@Component
@OutInterceptors(interceptors = { "com.mp.utils.CDATAOutInterceptor" })
@WebService(serviceName = "iMPService", endpointInterface = "com.mp.service.IMPService")
public class MPServiceImpl implements IMPService {
...
}

 

 

 

 

import javax.xml.stream.XMLStreamWriter;

import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.staxutils.StaxUtils;
public class CDATAOutInterceptor extends AbstractPhaseInterceptor {
	public CDATAOutInterceptor() {
		super(Phase.WRITE);
	}

	@Override
	public void handleMessage(Message message) {
		message.put("disable.outputstream.optimization", Boolean.TRUE);
		XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(message
				.getContent(OutputStream.class));
		message.setContent(XMLStreamWriter.class, new CDATAXMLStreamWriter(
				writer));
	}
}

 

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.apache.cxf.staxutils.DelegatingXMLStreamWriter;

public class CDATAXMLStreamWriter extends DelegatingXMLStreamWriter {

	private String currentElementName;

	public CDATAXMLStreamWriter(XMLStreamWriter writer) {
		super(writer);
	}

	@Override
	public void writeCharacters(String text) throws XMLStreamException {
		boolean useCData = isNeedCData();
		if (useCData) {
			super.writeCData(text);
		} else {
			super.writeCharacters(text);
		}
	}

	private boolean isNeedCData() {
              //自己拓展哪些属性需要处理CDATA
		return true;
	}

	public void writeStartElement(String prefix, String local, String uri)
			throws XMLStreamException {
		currentElementName = local;
		super.writeStartElement(prefix, local, uri);
	}
}

 

 

 

 

你可能感兴趣的:(WebService CXF 解决 CDATA)