Bem-vindo ao exemplo de Serviços Web Restful XML e JSON da Spring. Algum tempo atrás, escrevi um artigo sobre JSON da Spring REST e recebi muitos comentários perguntando como alterar o programa para oferecer suporte a XML. Também recebi alguns e-mails perguntando como fazer com que a aplicação suporte tanto XML quanto JSON.
XML e JSON da Spring REST
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 da Spring
Agora, faça as seguintes alterações no arquivo de configuração do feijão da primavera.
-
Defina um feijão do tipo
Jaxb2RootElementHttpMessageConverter
.<beans:bean id="xmlMessageConverter" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"> </beans:bean>
-
Adicione o feijão configurado acima à propriedade
messageConverters
deRequestMappingHandlerAdapter
.<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 feijão 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
. Portanto, adicione isso à nossa classe de modelo Employee
. Employee.java
@XmlRootElement
public class Employee implements Serializable{
//nenhuma alteração no código
}
Isso é tudo, terminamos. Nossa aplicação Spring oferecerá suporte tanto para JSON quanto para XML. Ela até mesmo aceitará solicitações XML com resposta JSON e vice-versa. Abaixo estão algumas capturas de tela mostrando isso em ação. OBSERVAÇÃO: 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. Solicitaçã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 para o exemplo de serviços da Web Restful com Spring, oferecendo suporte tanto para XML quanto para JSON. Você pode ver o quão fácil é estender o framework Spring, essa é uma das principais razões para a popularidade do Spring.
Source:
https://www.digitalocean.com/community/tutorials/spring-rest-xml-and-json-example