- Sản phẩm & Dịch vụSản phẩm & Dịch vụ
- Giải phápGiải pháp
- Bảng giáBảng giá
- Công tyCông ty
- Tài liệuTài liệu
vi
vi
Chuyên mục với các bài viết hướng dẫn, nghiên cứu và phân tích chi tiết về kỹ thuật, các xu hướng công nghệ mới nhất dành cho lập trình viên.
Technical Writer
I have over 5 years of experience writing technical documentation for tech products, making them accessible and user-friendly. My focus is always on providing clear and precise information. @#@ Tôi đã có hơn 5 năm kinh nghiệm viết tài liệu kỹ thuật cho các sản phẩm công nghệ, giúp người dùng dễ dàng tiếp cận và sử dụng. Tôi luôn tập trung vào việc cung cấp thông tin chính xác và dễ hiểu.
Thảo luận (0)
Đăng nhập để thảo luận
Khi xây dựng REST API, JSON thường là định dạng mặc định. Nhưng trong trường hợp một client yêu cầu định dạng XML thì sao? Bài viết này sẽ hướng dẫn bạn cách cấu hình Spring REST API để trả về XML và JSON theo yêu cầu của client.

Vì chúng ta sẽ chỉnh sửa dựa trên một project có sẵn, đầu tiên bạn cần tải nó về từ liên kết này.
Sau đây, ta sẽ thực hiện các thay đổi sau trong file cấu hình Spring bean.
Jaxb2RootElementHttpMessageConverter.<beans:bean id="xmlMessageConverter" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"> </beans:bean>
messageConverters của 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>
Sau các thay đổi trên, file cấu hình Spring bean servlet-context.xml hoàn chỉnh của chúng ta sẽ có dạng như sau:
<?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>
Chúng ta đã biết để hỗ trợ việc marshal (chuyển đổi một Java object thành XML) với JAXB cho một class, ta cần thêm annotation @XmlRootElement cho class đó. Vì vậy, hãy thêm annotation này vào model class trong Employee.java.
@XmlRootElement
public class Employee implements Serializable{
//no change in code
}
Ứng dụng Spring của chúng ta giờ đây sẽ hỗ trợ cả JSON lẫn XML. Nó thậm chí còn hỗ trợ request XML đi kèm response JSON và ngược lại.
Dưới đây là một vài hình minh họa cho kết quả thực tế. Lưu ý là bài này sử dụng ứng dụng Postman trong Chrome, nhưng bạn có thể dùng bất kỳ REST client nào để kiểm thử.
Response dạng XML: Cần đảm bảo truyền header Accept là “application/xml”.

Response dạng JSON: Cần đảm bảo truyền header Accept là “application/json”.

Request XML với Response JSON: Cần đảm bảo header Accept là “application/json” và header Content-Type là “text/xml” như trong các hình dưới đây.


Như vậy, chỉ với vài thay đổi nhỏ trong cấu hình và một annotation, ứng dụng Spring REST của bạn đã có thể linh hoạt phục vụ cả định dạng XML lẫn JSON. Điều này một lần nữa cho thấy sức mạnh và sự tiện lợi của Spring Framework trong việc xây dựng các web API hiện đại để đáp ứng tốt hơn các yêu cầu đa dạng từ phía client.