Ejemplo de Spring REST XML y JSON

Bienvenido al ejemplo de Servicios Web Restful XML y JSON de Spring. Hace algún tiempo escribí un artículo sobre JSON REST de Spring y recibí muchos comentarios preguntando cómo cambiar el programa para admitir XML. También recibí algunos correos electrónicos preguntando cómo hacer que la aplicación admita tanto XML como JSON.

XML y JSON REST de Spring

I thought to write an article about Spring REST XML and JSON application where I will show you how easily we can extend the existing application to support XML. Since I will be making changes to the existing project, make sure you first download it from below link.

Descarga el Proyecto de Servicio Web Restful de Spring

Ahora realiza los siguientes cambios en el archivo de configuración de bean de Spring.

  1. Define un bean del tipo Jaxb2RootElementHttpMessageConverter.

    <beans:bean id="xmlMessageConverter" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter">
    </beans:bean>
    
  2. Agrega el bean configurado anteriormente a la propiedad messageConverters del RequestMappingHandlerAdapter.

    <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>
    

Después de los cambios anteriores, nuestro archivo de configuración final de beans de Spring se verá así. 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>

Sabemos que para trabajar con la marshalling de JAXB para una clase, necesitamos anotarla con la anotación @XmlRootElement. Entonces agregue esto a nuestra clase de modelo Employee. Employee.java

@XmlRootElement
public class Employee implements Serializable{

//sin cambios en el código
}

¡Listo, hemos TERMINADO! Nuestra aplicación Spring admitirá tanto JSON como XML. Incluso admitirá solicitudes XML con respuesta JSON y viceversa. A continuación, se muestran algunas capturas de pantalla que muestran esto en acción. NOTA: Estoy utilizando la aplicación Postman Chrome para esto; puedes usar cualquier cliente REST para realizar estas pruebas.

1. Respuesta XML: Asegúrate de pasar el encabezado Accept como “application/xml”.
2. Respuesta JSON: Asegúrate de pasar el encabezado Accept como “application/json”.
3. Solicitud XML con respuesta JSON: Asegúrate de que el encabezado Accept sea “application/json” y el encabezado Content-Type sea “text/xml”, como se muestra en las imágenes a continuación.

Eso es todo para el ejemplo de servicios web RESTful de Spring que admiten tanto XML como JSON. Puedes ver lo fácil que es extender el marco de Spring; esta es una de las principales razones de la popularidad del marco de Spring.

Source:
https://www.digitalocean.com/community/tutorials/spring-rest-xml-and-json-example