Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 790
gtludwig Avatar asked Nov 20 '25 16:11

gtludwig


1 Answers

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

  • Part 1 - The Database
  • Part 2 - JPA Entities
  • Part 3 - JAXB Bindings
  • Part 4 - The RESTFul Service
  • Part 5 - The Client
like image 62
bdoughan Avatar answered Nov 22 '25 05:11

bdoughan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!