Пример Spring REST XML и JSON
Добро пожаловать в пример Spring Restful Web Services XML и JSON. Некоторое время назад я написал статью о Spring REST JSON и получил много комментариев с вопросами о том, как изменить программу для поддержки XML. Я получил несколько писем, в которых также спрашивали, как сделать так, чтобы приложение поддерживало как XML, так и JSON.
Spring REST XML и JSON
Я подумал написать статью о приложении Spring REST XML и JSON, где я покажу вам, как легко мы можем расширить существующее приложение для поддержки XML. Поскольку я буду вносить изменения в существующий проект, убедитесь, что вы сначала загрузили его по ссылке ниже.
Загрузить Spring Restful Webservice Project
Теперь внесите следующие изменения в файл конфигурации bean-компонента Spring.
-
Define a bean of type
Jaxb2RootElementHttpMessageConverter
.<beans:bean id="xmlMessageConverter" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"> </beans:bean>
-
Add above configured bean to
RequestMappingHandlerAdapter
propertymessageConverters
.<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <beans:property name="messageConverters"> <beans:list> <beans:ref bean="jsonMessageConverter"/> <beans:ref bean="xmlMessageConverter"/> </beans:list> </beans:property> </beans:bean>
После вышеуказанных изменений наш окончательный файл конфигурации bean-компонента Spring будет выглядеть так, как показано ниже. 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 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<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 class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<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" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>
<beans:bean id="xmlMessageConverter" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter">
</beans:bean>
<context:component-scan base-package="com.journaldev.spring.controller" />
</beans:beans>
Мы знаем, что для работы с сортировкой JAXB для класса нам нужно аннотировать его аннотацией @XmlRootElement
. Поэтому добавьте это в наш модельный класс Employee
. Сотрудник.java
@XmlRootElement
public class Employee implements Serializable{
//no change in code
}