---
title: "jersey 简单使用"
author: "annybz"
date: "2013-11-25T17:34:07Z"
tags: []
categories: ["移动开发"]
slug: "jersey"
draft: false
lastmod: "2013-11-25T17:34:07Z"
id: 1980492
url: "https://annybz.iteye.com/blog/1980492"
---

\[size=large] 之前对于Webservice已经看了很多，包括axis，axissession校验（保持会话），cxf，jsr311等等，今天看了jersey，简单的写了一个例子。分享给入门的朋友。 jersey是一种restful框架，使用它为我们提供接口。有三块重要的东西，jersey-server，jersey-core, 集成（与spring等等） codeing之前，先看看需要什么东西，也就是jar 我用的是maven工程，配置了 org.glassfish.jersey.core jersey-server 2.4.1 org.glassfish.jersey.core jersey-client 2.4.1 com.sun.xml.bind jaxb-impl 2.1.13 com.sun.jersey jersey-json 1.17.1 com.sun.jersey jersey-core 1.17.1 javax.ws.rs javax.ws.rs-api 2.0 都是在jersey开发中需要使用的，我加的比较全面。 说明一下：工程名字jerseydemo，包名 cn.thinkjoy.jerseydemo.resources. 在web.xml中配置 Jersey REST Service com.sun.jersey.spi.container.servlet.ServletContainer com.sun.jersey.config.property.packages cn.thinkjoy.jerseydemo.resources 1 Jersey REST Service /rest/* 然后在包下写类文件： import javax.annotation.Resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/hello") public class HelloResource { @GET @Produces(MediaType.TEXT\_HTML) public String sayHello() { return "hello world !  
111"; } } 相关解释： 资源类（Resource Class）：注意，资源类是一个简单的 Java 对象 (POJO)，可以实现任何接口。这增加了许多好处，比如可重用性和简单。 注释（Annotation）：在 javax.ws.rs.* 中定义，是 JAX-RS (JSR 311) 规范的一部分。 @Path：定义资源基 URI。由上下文根和主机名组成，资源标识符类似于 http://localhost:8080/Jersey/rest/hello。 @GET：这意味着以下方法可以响应 HTTP GET 方法。 @Produces：以纯文本方式定义响应内容 MIME 类型。 我用的jetty启动服务，代码如下： import org.mortbay.jetty.Server; import org.springside.modules.test.utils.JettyUtils; public class StartServer { public static final int PORT = 8080; public static final String CONTEXT = "/jerseydemo"; public static final String BASE\_URL = "http://localhost:8080/jerseydemo"; public static void main(String\[] args) throws Exception { Server server = JettyUtils.buildNormalServer(PORT, CONTEXT); server.start(); System.out.println("Hit Enter in console to stop server"); try { if (System.in.read() != 0) { server.stop(); System.out.println("Server stopped"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 运行StartServer之后，在本地浏览器窗口 输入地址： http://localhost:8080/jerseydemo/rest/hello 可以看到返回的结果 结果就不给大家附上了。 这是一个很简单的入门级联系。 \[/size]