REST with Java (JAX-RS) 使用 Jersey [英] REST with Java (JAX-RS) using Jersey
问题描述
我通过 Jersey in Java (JAX-RS) 开发了一个安静的 Web 服务:http://www.vogella.com/articles/REST/article.html
I developed a restful web service via Jersey in Java (JAX-RS) : http://www.vogella.com/articles/REST/article.html
然后我使用 Hibernate 技术将数据映射到数据库.
Then I used the Hibernate Technology to map the data to the database.
最后我开发了一个安卓应用来显示数据.
Finally I developed an android application to display data.
这是我的 Web 服务中的一个方法示例:
This is an example of a method in my Web Service :
@GET
@Path("/project_id/username/get/{projectId}/{username}/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response deliverableList(@PathParam("projectId") long projectId,
@PathParam("username") String username) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<Deliverable> list = null;
try {
list= (List<Deliverable>) session.createQuery(
"from Deliverable as d where d.project.id= :id").setLong("id", projectId).list();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return Response.status(201).entity(list).build();
}
如您所见,我使用Response.status(201).entity(list).build()"来传输数据列表.这是一个好方法吗?如果不是,您对传输数据有什么建议.请用一些代码和例子来支持你的解释.
as you see I used "Response.status(201).entity(list).build()" to transfer the list of data. Is it a good way? if not what is your suggestion to transfer the data. Please support your explanation with some codes and examples.
推荐答案
- Response.ok().enity(object).build() 是返回数据的正确方式
- 您确实希望将休眠内容移至数据访问层...与您的服务层混合管理将很难
- 我完全不同意 smcg 关于使用辅助方法将 java 映射到 json.除非您有非常复杂的要求,否则请在您的 bean 上使用 jax-rs 注释:请参阅 http://wiki.fasterxml.com/JacksonAnnotations
这篇关于REST with Java (JAX-RS) 使用 Jersey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!