Exemplo de Spring REST XML e JSON

Bem-vindo ao exemplo de Serviços Web Restful Spring XML e JSON. Algum tempo atrás, escrevi um artigo sobre Spring REST JSON e recebi muitos comentários perguntando como alterar o programa para suportar XML. Também recebi alguns e-mails perguntando como fazer com que a aplicação suporte tanto XML quanto JSON.

Spring REST XML e JSON

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.

Download do Projeto de Serviço Web Restful Spring

Agora faça as seguintes alterações no arquivo de configuração de beans do Spring.

  1. Defina um bean do tipo Jaxb2RootElementHttpMessageConverter.

    <beans:bean id="xmlMessageConverter" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter">
    </beans:bean>
    
  2. Adicione o bean configurado acima à propriedade messageConverters do 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>
    

Após as alterações acima, nosso arquivo de configuração final do bean Spring ficará assim. 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 trabalhar com a marshalling JAXB para uma classe, precisamos anotá-la com a anotação @XmlRootElement. Então adicione isso à nossa classe de modelo Employee. Employee.java

@XmlRootElement
public class Employee implements Serializable{

//nenhuma mudança no código
}

Aqui está, estamos PRONTOS. Nossa aplicação Spring suportará tanto JSON quanto XML. Ela até mesmo suportará requisições XML com resposta JSON e vice-versa. Abaixo estão algumas capturas de tela mostrando isso em ação. NOTA: Estou usando o aplicativo Postman Chrome para isso, você pode usar qualquer cliente REST para este teste. 1. Resposta XML: Certifique-se de passar o cabeçalho Accept como “application/xml”. 2. Resposta JSON: Certifique-se de passar o cabeçalho Accept como “application/json”. 3. Requisição XML com Resposta JSON: Certifique-se de que o cabeçalho Accept seja “application/json” e o cabeçalho Content-Type seja “text/xml”, conforme mostrado nas imagens abaixo. Isso é tudo para o exemplo de serviços web Restful do Spring que suporta tanto XML quanto JSON. Você pode ver como é fácil estender o framework Spring, essa é uma das principais razões da popularidade do framework Spring.

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