欢迎使用Spring Restful Web服务XML和JSON示例。不久前我写了一篇关于
现在对Spring Bean配置文件执行以下更改。
- 定义类型的bean
Jaxb2RootElementHttpMessageConverter
.<beans:bean id="xmlMessageConverter"> </beans:bean>
- 将上面配置的bean添加到
RequestMappingHandlerAdapter
propertymessageConverters
.<beans:bean> <beans:property name="messageConverters"> <beans:list> <beans:ref bean="jsonMessageConverter"/> <beans:ref bean="xmlMessageConverter"/> </beans:list> </beans:property> </beans:bean>
在以上更改之后,我们最终的Spring Bean配置文件如下所示。
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet"s request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean>
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- Configure to plugin JSON as request and response in method handler -->
<beans:bean>
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter"/>
<beans:ref bean="xmlMessageConverter"/>
</beans:list>
</beans:property>
</beans:bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter">
</beans:bean>
<beans:bean id="xmlMessageConverter">
</beans:bean>
<context:component-scan base-package="com.journaldev.spring.controller" />
</beans:beans>
我们知道,对于一个类使用JAXB编组,我们需要用@XmlRootElement
annotation. So add this to our Employee
model class.
Employee.java
@XmlRootElement
public class Employee implements Serializable{
//no change in code
}
就这样,我们结束了。我们的Spring应用程序将同时支持JSON和XML。它甚至支持XML请求和JSON响应,反之亦然。下面是一些屏幕截图显示了这一点。
注意:我使用的是Postman Chrome应用程序,您可以使用任何rest客户端进行此测试。
1XML响应:确保将Accept header作为&8220;application/xml&8221;传递;。
2JSON响应:确保将Accept header作为&8220;application/json&8221;传递;。
三。带有JSON响应的XML请求:确保Accept header为“;application/json”;并且Content Type header是“;text/xml”;,如下图所示。
这是Spring Restful Web服务的全部示例,支持XML和JSON。您可以看到扩展Spring框架是多么容易,这是Spring框架流行的主要原因之一。