简体   繁体   中英

how can I output a XML file to a REST web service in Java so another application can consume this XML?

I need to output an XML file from one application to another, but I'd like not to have to write this XML somewhere and then reading this file on the other application.

Both are Java applications and (so far!) I'm using XStream.

How can I do it?

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

JAXB (JSR-222) is the default binding layer for The Java API for RESTful Web Services (JAX-RS) . This means you can just create a service that returns POJOs and all the to/from XML conversion will be handled for you.

Below is an example JAX-RS service that looks up an instance of Customer using JPA and returns it to XML. The JAX-RS implementation will leverage JAXB to do the actual conversion automatically.

package org.example;

import java.util.List;
import javax.ejb.*;
import javax.persistence.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

@Stateless
@LocalBean
@Path("/customers")
public class CustomerService {

    @PersistenceContext(unitName="CustomerService", 
                        type=PersistenceContextType.TRANSACTION)
    EntityManager entityManager;

    @GET
    @Produces(MediaType.APPLICATION_XML)
    @Path("{id}")
    public Customer read(@PathParam("id") long id) {
        return entityManager.find(Customer.class, id);
    }

}

Full Example

对于负载较重的应用程序,另一种方法是使用谷歌ProtoBuf而不是XML格式 - 这允许您最小化应用程序之间的流量并提高性能。从我的角度来看,XML用于数据传输不是一个好主意。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM