基础
pom.xml
首先需要引入eclipselink包:
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0</version>
</dependency>
jaxb.properties
实体类包下面需要添加jaxb.properties文件:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
entity
实体类使用如下注解:
package com.dinpay.dpp.rss.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Person")
public class Person {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
接收XML
控制层及配置文件
controller接口使用@ResponseBody和@RequestBody
方法一:
使用Jaxb2RootElementHttpMessageConverter映射成实体类
package com.dinpay.dpp.rss.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dinpay.dpp.rss.model.Person;
import com.dinpay.dpp.rss.model.PersonRiskInfo;
/**
*
* created by wjx on 2016-12-23
*/
@Controller
@RequestMapping("/RSSSimulation")
public class RSSSimulationController {
private static Logger logger = LoggerFactory.getLogger(RSSSimulationController.class);
@RequestMapping(value = "/sendPerson")
@ResponseBody
public Person sendPerson(HttpServletRequest request, @RequestBody Person person) {
logger.info(person.getId());
logger.info(person.getName());
return person;
}
}
springmvc.xml配置
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" index="0"></constructor-arg>
</bean>
<bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter">
</bean>
</list>
</property>
</bean>
方法二:
package com.dinpay.dpp.rss.controller;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dinpay.dpp.rss.utils.message.RequestBuilder;
import com.dinpay.dpp.rss.utils.message.ResponseParser;
/**
*
* created by wjx on 2016-12-23
*/
@Controller
@RequestMapping("/RSSSimulation")
public class RSSSimulationController {
private static Logger logger = LoggerFactory.getLogger(RSSSimulationController.class);
private RequestBuilder requestBuilder = new RequestBuilder();
private ResponseParser responseParser = new ResponseParser();
@RequestMapping(value = "/sendPerson2")
public Person sendPerson2(HttpServletRequest request, @RequestBody DOMSource person) {
String xml = parseDOMSource(person);
logger.info(xml);
Person p = new Person();
p.setId("1");
p.setName("2");
return p;
}
public String parseDOMSource(DOMSource person) {
try {
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(person, result);
return writer.toString();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
springmvc.xml配置
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" index="0"></constructor-arg>
</bean>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter">
</bean>
</list>
</property>
</bean>
测试类:
package com.dinpay.ddp.rss.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dinpay.dpp.rss.model.Person;
import com.dinpay.dpp.rss.utils.http.HttpClientUtils;
/**
*
* created by wjx on 2016-12-23
*/
public class HttpClientTest {
private static Logger logger = LoggerFactory.getLogger(HttpClientTest.class);
public static void main(String args[]) {
String requestMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" //
+ "<Person>" //
+ " <Id>22</Id>" //
+ " <Name>李四</Name>" //
+ "</Person>";
String url = "http://192.168.23.22:8080/RSSSimulationWeb/RSSSimulation/queryPersonRiskInfo";
Person person = new Person();
person.setId("1");
person.setName("2");
String result = HttpClientUtils.doPostXml(url, requestMsg);
logger.info("result:" + result);
}
}
package com.dinpay.dpp.rss.utils.http;
import java.io.IOException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClientUtils {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
public static String doPostXml(String url, String xml) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(xml, ContentType.APPLICATION_XML);
httpPost.setHeader("Content-type", "application/xml; charset=ISO-8859-1");
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
// resultString = EntityUtils.toString(response.getEntity(),
// "utf-8");
} catch (Exception e) {
logger.error("HttpClientUtils doPostXml error", e);
} finally {
try {
response.close();
} catch (IOException e) {
logger.error("HttpClientUtils doPostXml response close error", e);
}
}
return resultString;
}
}
返回XML
在上述案例基础上,增加控制层及springmvc.xml配置
控制层
直接返回对象
@RequestMapping(value = "/sendPerson2")
@ResponseBody
public Person sendPerson2(HttpServletRequest request, @RequestBody DOMSource person) {
String xml = parseDOMSource(person);
logger.info(xml);
Person p = new Person();
p.setId("1");
p.setName("2");
return p;
}
springmvc.xml配置
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" index="0"></constructor-arg>
</bean>
<!-- XML转换器,有双重作用,在接收XML参数时用于转换为实体对象,在返回参数时把返回对象转换为XML格式 -->
<bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter">
</bean>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter">
</bean>
</list>
</property>
</bean>
<!-- 返回值映射配置 -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<!-- 返回格式转换管理器,如果此处没有配置,则请求方请求时head要增加返回类型 setHeader("Accept", "application/xml; charset=UTF-8"); -->
<property name="contentNegotiationManager">
<bean class="org.springframework.web.accept.ContentNegotiationManager">
<constructor-arg>
<bean class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
<constructor-arg>
<map>
<entry key="json" value="application/json;charset=utf-8"/>
<entry key="xml" value="application/xml;charset=utf-8"/>
</map>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"></bean>
<bean name="jaxb2MarshallingView" class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<!-- 具体要转换的类 -->
<!--
<property name="classesToBeBound">
<array>
<value>com.dinpay.dpp.rsss.model.Person</value>
<value>com.dinpay.dpp.rss.model.PersonRiskInfo</value>
<value>com.dinpay.dpp.rss.model.MerchantRiskInfo</value>
</array>
</property>
-->
<!-- 具体要转换的所有包中的类 -->
<property name="packagesToScan">
<array>
<value>com.dinpay.dpp.rsss.model</value>
<value>com.dinpay.dpp.rss.model</value>
</array>
</property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>