---
title: "jersey demo"
author: "萧_瑟"
date: "2012-08-28T16:33:17Z"
tags: ["WebService", "jersey"]
categories: ["编程语言"]
slug: "jersey-demo"
draft: false
lastmod: "2012-08-28T16:39:06Z"
id: 1665448
url: "https://royal2xiaose.iteye.com/blog/1665448"
---

同样是Maven构建的项目，不解释。

 

 

项目目录结构：

![](http://dl.iteye.com/upload/attachment/0072/9847/4519a883-806c-3d18-b3d4-7760cc67ede0.png)

 

 

pom.xml

```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.royal</groupId>
  <artifactId>jerseyDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>jerseyDemo</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey</artifactId>
      <version>0.8-ea</version>
    </dependency>
    
  </dependencies>
</project>
```

 

有些包down不下来，请手动下载后加入.m2/repository库中。

 

web.xml

```
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
    <servlet>
        <servlet-name>Jersey</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.royal.resources</param-value>
        </init-param>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>Jersey</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
```

 

注意：自定义拦截路径&lt;url-pattern&gt;/rest/\*&lt;/url-pattern&gt; 

 

 

User.java

```
package com.royal.model;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlRootElement;

/**
 * 
 *这里用到的表示它返回的时候的类型，即此User类可以用于XML返回。
 */
@XmlRootElement
public class User implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private String name;
	
	private String password;
	
	public User(){
		
	}
	
	public User(String name, String password){
		this.name = name;
		this.password = password;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	public String toString(){
		return "Name:" + name + ",Password:" + password;
	}

}
```

 

 

UserService.java

```
package com.royal.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.ProduceMime;
import javax.ws.rs.core.MediaType;

import com.royal.model.User;

@Path("/userService")
public class UserService {
	
	/**
	 * Hello World
	 */
	@GET
	@ProduceMime(MediaType.TEXT_PLAIN)
    public String hello() {  
        return "Jersey Hello World!";  
    } 
	
	/**
	 * new a User
	 */
	@GET
	@Path("{name}/{password}")
	@ProduceMime(MediaType.APPLICATION_JSON)
	public User getUser(@PathParam("name") String name, @PathParam("password") String password){
		return new User(name,password);
	}
	
}
```

 

 

 

客户端测试：

 

UserClient.java

```
package com.royal.jerseyDemo;

import com.royal.model.User;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

public class UserClient {

	public static String root_uri = "http://localhost:8080/jerseyDemo/rest/userService";

	private Client client = null;

	public UserClient() {
		if (client == null) {
			client = Client.create();
		}
	}

	public static void main(String[] args) {
		UserClient uc = new UserClient();

		// hello world
		String hello_str = uc.hello();
		System.out.println(hello_str);

		// new a User
		User user = uc.getUser("royal", "2xiaose");
		System.out.println(user);
	}

	/**
	 * hello world
	 */
	public String hello() {
		 WebResource resource = client.resource(root_uri);
		 String str = resource.get(String.class);
		 return str;
	}

	/**
	 * new a User
	 */
	public User getUser(String name, String password) {
		WebResource resource = client.resource(root_uri);
		User user = resource.path(name + "/" + password).get(User.class);
		return user;
	}

}
```

 

注意 root\_uri

 

 

 

测试结果：

![](http://dl.iteye.com/upload/attachment/0072/9853/07ca2e86-c9e2-36f3-a1b7-d62ed90de443.png)

 

 

浏览器中输入：

 

http://localhost:8080/jerseyDemo/rest/userService             结果：

![](http://dl.iteye.com/upload/attachment/0072/9863/c150241d-a5fc-37d1-b31b-c3d272cf3fba.png)

 

 

http://localhost:8080/jerseyDemo/rest/userService/royal/2xiaose        结果：

![](http://dl.iteye.com/upload/attachment/0072/9861/a824979b-aee6-3d97-ba1d-be4b2f2f41f5.png)

 

 

参考：[http://www.ishang123.com/jishubowen/java/2012-08-01/126.html](http://www.ishang123.com/jishubowen/java/2012-08-01/126.html)