WebService返回XML/JSON文件 [英] WebService return a XML/JSON file
问题描述
我需要编写一个简单的Java Web服务,该服务可以XML/JSON文件的形式显示其输出.
I require to write a simple java webservice that could show its output in the form of a XML/JSON file.
例如,用户将单击链接或按钮,并且将执行一条简单的SQL语句SELECT * FROM PERSON
,并且上述SQL查询的结果应以XML/JSON文件的形式显示.
For example the user will click a link or a button, and a simple SQL statement would get executed SELECT * FROM PERSON
and the result of the above SQL query should be displayed in the form a XML/JSON file.
我已经用Google搜索了几次,但是找不到合适的教程或示例代码.有人可以通过提供示例代码或教程来为我提供帮助.
I have googled this several times but failed to find a suitable tutorial or a sample code. Can some one help me by providing a sample code or a tutorial that would help me.
推荐答案
您可以使用 JAX-RS 执行以下操作:
You could do something like the following with JAX-RS:
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, MediaType.APPLICATION_JSON})
@Path("{id}")
public Customer read(@PathParam("id") long id) {
return entityManager.find(Customer.class, id);
}
}
完整示例
- Part 1 - The Database
- Part 2 - Mapping the Database to JPA Entities
- Part 3 - Mapping JPA entities to XML (using JAXB)
- Part 4 - The RESTful Service
- Part 5 - The Client
这篇关于WebService返回XML/JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!