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<Message> {
	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);
	}
}

?

?

?

?

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。