【问题标题】:Auto marshalling in JAX RSJAX RS 中的自动编组
【发布时间】:2012-10-29 11:32:50
【问题描述】:

我曾使用 Jax WS 并使用 wsgen 和 wsimport 来自动编组自定义类型。我也可以将 wsgen 与 JaxRS 一起使用吗?如果是这样,我应该将 wsgen 生成的文件放在哪里以及如何引用它们?我只是不想自己处理使用 JAXB 并使用 wsgen 作为快捷方式。

【问题讨论】:

    标签: web-services rest wsgen


    【解决方案1】:

    默认情况下,JAX-RS 实现将使用 JAXB 将域对象与 XML 转换为 application/xml 媒体类型。在下面的示例中,将在 Customer 类上创建 JAXBContext,因为它在 RESTful 操作中显示为参数和/或返回类型。

    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;
    
        @POST
        @Consumes(MediaType.APPLICATION_XML)
        public void create(Customer customer) {
            entityManager.persist(customer);
        }
    
        @GET
        @Produces(MediaType.APPLICATION_XML)
        @Path("{id}")
        public Customer read(@PathParam("id") long id) {
            return entityManager.find(Customer.class, id);
        }
    
    }
    

    在单个类上创建的JAXBContext 还将为所有可传递引用类创建元数据,但这可能不会引入从您的 XML 模式生成的所有内容。您将需要利用 JAX-RS 上下文解析器机制。

    package org.example;
    
    import java.util.*;
    import javax.ws.rs.Produces;
    import javax.ws.rs.ext.*;
    import javax.xml.bind.*;
    import org.eclipse.persistence.jaxb.JAXBContextFactory;
    
    @Provider
    @Produces("application/xml")
    public class CustomerContextResolver implements ContextResolver<JAXBContext> {
    
        private JAXBContext jc;
    
        public CustomerContextResolver() {
            try {
                jc = JAXBContext.newInstance("com.example.customer" , Customer.class.getClassLoader());
            } catch(JAXBException e) {
                throw new RuntimeException(e);
            }
        }
    
        public JAXBContext getContext(Class<?> clazz) {
            if(Customer.class == clazz) {
                return jc;
            }
            return null;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-07
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多