1.环境信息
开发工具:idea
接口测试工具:soapui
编程语言:java
项目环境:jdk1.8
webservice:jdk自带的jws
处理xml:jdk自带的jaxb
2.涉及代码
package org.example.webdemo;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface JaxbWebService {
@WebMethod
public String dealXml(String xml);
}
package org.example.webdemo;
import javax.jws.WebService;
@WebService
public class JaxbWebServiceImpl implements JaxbWebService {
@Override
public String dealXml(String xml) {
String result ="";
if(xml !=null && xml.length()!=0){
RootBean rootBean = (RootBean)JaxbUtil.convertXmlToObject(xml, RootBean.class);
String bussinessBody = rootBean.getBody();
BussinessBean bussinessBean = (BussinessBean)JaxbUtil.convertXmlToObject(bussinessBody, BussinessBean.class);
result = bussinessBean.getName();
System.out.println(String.format("成功获取到第二层的标签name的值:%s",result));
}
return result;
}
}
package org.example.webdemo;
import lombok.extern.slf4j.Slf4j;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
@Slf4j
public class JaxbUtil {
public static Object convertXmlToObject(String xml,Class<?> clazz) {
Object xmlObj = null;
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
StringReader sReader = new StringReader(xml);
xmlObj = unmarshaller.unmarshal(sReader);
} catch (Exception e) {
log.error("Xml转换对象失败", e);
}
return xmlObj;
}
}
package org.example.webdemo;
import lombok.Data;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@Data
@XmlRootElement(name = "Root")
@XmlAccessorType(XmlAccessType.FIELD)
public class RootBean {
@XmlElement(name = "Body")
public String body;
}
package org.example.webdemo;
import lombok.Data;
import javax.xml.bind.annotation.*;
@Data
@XmlRootElement(name = "Bussiness")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = { "name", "action"})
public class BussinessBean {
@XmlElement(name = "Name")
public String name;
@XmlElement(name = "Action")
public String action;
}
package org.example.webdemo;
import javax.xml.ws.Endpoint;
public class JaxbWebServicePublish {
public static void main(String[] args) {
Endpoint.publish("http://localhost:8080/websevice",new JaxbWebServiceImpl());
}
}
3.测试验证
3.1启动 webservice服务
3.2 soapui调用接口
3.2.1 传递报文信息
<![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<Root>
<Body><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<Bussiness>
<Name>xiaoming</Name>
<Action>run</Action>
</Bussiness>]]]]>><![CDATA[</Body></Root>]]>
3.2.2 soapui工具调用接口
4.最终总结
4.1 传递参数的xml声明行前面存在换行或空格出错
声明行:<?xml version="1.0" encoding="UTF-8"?>
根节点的上面这个声明行不允许出现空格与空行,如果出现空行或空格后端会解析出错。
4.1.1 复现问题
拿到的报文在xmlspy验证也不通过的