Java Restful Web Services (一)

REST(Representational State Transfer,表述性状态转移),是Roy Thomas Fielding在他2000年的博士论文《Architectural Styles and the Design of Network-based Software Architectures》提出,与复杂的SOAPXML-RPC相比,REST更加简洁,越来越多的Web服务开始采用REST风格设计和实现。Rest是一种架构风格,在这样的架构风格中,对象被抽象成为一种资源,资源的命名使用概念清晰的名词来定义,HTTP+URI+XML是Rest的基本实现形式。JAX-RS是JAVA EE6 引入的一个新技术,是Java领域的Rest式的Web服务的标准规范,JAX-RS即Java API for RESTful Web Services,是一个Java 编程语言的应用程序接口,支持按照表述性状态转移(REST)架构风格创建Web服务。JAX-RS使用了Java SE5引入的Java标注来简化Web服务的客户端和服务端的开发和部署。Jersey是JAX-RS标准的参考实现。

基于Jersey开发Restful服务,新建一个Web工程,引入我们需要的jar包,Jersey最新参考实现Jar包可通过Jersey官方网站下载

新建一个package,定义资源类。

package cn.com.abc.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

@Path("helloworld")
public class HelloWorldResource {
	public static final String CLICHED_MESSAGE = "Hello World!";

	
	@GET
	@Path("/before")
	@Produces("text/plain")
	public String getHelloBefore() {
		return "hello before";
	}
	
	
	@GET
	@Produces("text/plain")
	public String getHello() {
		return CLICHED_MESSAGE;
	}
	
	@GET
	@Path("/{param}")
	@Produces("text/plain") 
	public String getHello(@PathParam("param")  String username) {
		return "Hello Path Param " + username;
	}
	
	
	@GET
	@Path("/user")
	@Produces("text/plain")
	public String getHelloWithQuery(@QueryParam("param") String username) {
		return "Hello Query Param " + username;
	}
	

	
}





修改web.xml

<servlet>
    <servlet-name>Way REST Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>      
      <param-value>cn.com.abc.rest;com.fasterxml.jackson.jaxrs.json</param-value>
    </init-param>    
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Way REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>

如果您的资源实现类放在不同的包中,那么您可在属性param-value中指定多个包名用以对外公布REST服务接口。 接下来是我们的测试类。

package cn.com.abc.test;

import static org.junit.Assert.*;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class HelloWorldResourceTest {

	private WebTarget target;
	public static final String BASE_URI = "http://localhost:8090/NoteMail/rest/";

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		System.out.println("setUpBeforeClass");
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		System.out.println("tearDownAfterClass");
	}

	@Before
	public void setUp() throws Exception {
		System.out.println("setUp");
		Client c = ClientBuilder.newClient();
		target = c.target(BASE_URI);
		System.out.println(target.getUri());
	}

	@After
	public void tearDown() throws Exception {
		System.out.println("tearDown");
	}

	
	
	@Test
	public void testGetHello() {

		String responseMsg = target.path("helloworld").request()
				.get(String.class);		
		assertEquals("Hello World!", responseMsg);
		
	}
	
	@Test
	public void testGetHelloWithPathParam() {

		String responseMsg = target.path("helloworld/ABC").request().get(String.class);		
		assertEquals("Hello Path Param ABC", responseMsg);
		
	}
	
	
	@Test
	public void testGetHelloWithQueryParam() {

		String responseMsg = target.path("helloworld/user").queryParam("param", "ABC").request().get(String.class);		
		assertEquals("Hello Query Param ABC", responseMsg);
		
	}
	
	
	@Test
	public void testGetHelloBefore() {

		String responseMsg = target.path("helloworld/before/").request()
				.get(String.class);
		assertEquals("hello before", responseMsg);

	}


}

在资源实现类中包含了两个不同注解的方法@PathParam和@QueryParam,两种不同的方法调用方式也略有不同。各种不同的注解使用将在下一篇中介绍。

对于@PathParam,其调用方式为:

http://localhost:8090/NoteMail/rest/helloworld/ABC

对于@QueryParam,其调用方式为

http://localhost:8090/NoteMail/rest/helloworld/user?param=ABC

我们通过访问“服务根路径/application.wadl”(本示例为http://localhost:8090/NoteMail/rest/application.wadl)可以看到当前REST环境中所提供的REST服务器接口,WADL(Web Application Description Language)是用来描述基于HTTP的Rest式Web服务部署情况。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://wadl.dev.java.net/2009/02">
    <doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 2.15 2015-01-12 22:32:50"/>
    <doc xmlns:jersey="http://jersey.java.net/" jersey:hint="This is simplified WADL with user and core resources only. To get full WADL with extended resources use the query parameter detail. Link: http://localhost:8090/NoteMail/rest/application.wadl?detail=true"/>
    <grammars/>
    <resources base="http://localhost:8090/NoteMail/rest/">
        <resource path="helloworld">
            <method id="getHello" name="GET">
                <response>
                    <representation mediaType="text/plain"/>
                </response>
            </method>
            <resource path="/before">
                <method id="getHelloBefore" name="GET">
                    <response>
                        <representation mediaType="text/plain"/>
                    </response>
                </method>
            </resource>
            <resource path="/user">
                <method id="getHelloWithQuery" name="GET">
                    <request>
                        <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="param" style="query" type="xs:string"/>
                    </request>
                    <response>
                        <representation mediaType="text/plain"/>
                    </response>
                </method>
            </resource>
            <resource path="/{param}">
                <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="param" style="template" type="xs:string"/>
                <method id="getHello" name="GET">
                    <response>
                        <representation mediaType="text/plain"/>
                    </response>
                </method>
            </resource>
        </resource>
        <resource path="books">
            <method id="saveBook" name="POST">
                <request>
                    <representation mediaType="application/xml"/>
                    <representation mediaType="application/json"/>
                </request>
                <response>
                    <representation mediaType="application/xml"/>
                    <representation mediaType="application/json"/>
                </response>
            </method>
            <method id="getBooks" name="GET">
                <response>
                    <representation mediaType="application/json"/>
                    <representation mediaType="application/xml"/>
                </response>
            </method>
            <resource path="{bookid:[0-9]*}">
                <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="bookid" style="template" type="xs:int"/>
                <method id="updateBook" name="PUT">
                    <request>
                        <representation mediaType="application/xml"/>
                        <representation mediaType="application/json"/>
                        <representation mediaType="text/xml"/>
                    </request>
                    <response>
                        <representation mediaType="application/xml"/>
                        <representation mediaType="application/json"/>
                    </response>
                </method>
                <method id="deleteBook" name="DELETE">
                    <response>
                        <representation mediaType="*/*"/>
                    </response>
                </method>
                <method id="getBookByPath" name="GET">
                    <response>
                        <representation mediaType="application/xml"/>
                        <representation mediaType="application/json"/>
                    </response>
                </method>
            </resource>
            <resource path="/book">
                <method id="getBookByParam" name="GET">
                    <request>
                        <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="bookid" style="query" type="xs:int"/>
                    </request>
                    <response>
                        <representation mediaType="application/xml"/>
                        <representation mediaType="application/json"/>
                    </response>
                </method>
            </resource>
            <resource path="/booktest">
                <method id="sayHello" name="GET">
                    <response>
                        <representation mediaType="text/plain"/>
                    </response>
                </method>
            </resource>
        </resource>
        <resource path="users">
            <resource path="/{username}">
                <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="username" style="template" type="xs:string"/>
                <method id="getUserIgnore" name="GET">
                    <response>
                        <representation mediaType="text/plain"/>
                    </response>
                </method>
            </resource>
            <resource path="/{username: [a-zA-Z][a-zA-Z_0-9]*}">
                <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="username" style="template" type="xs:string"/>
                <method id="getUser" name="GET">
                    <response>
                        <representation mediaType="text/plain"/>
                    </response>
                </method>
            </resource>
        </resource>
        <resource path="/hellorestanother">
            <method id="sayHello" name="GET">
                <response>
                    <representation mediaType="text/plain"/>
                </response>
            </method>
            <resource path="/{param}">
                <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="param" style="template" type="xs:string"/>
                <method id="sayHelloToUTF8" name="GET">
                    <response>
                        <representation mediaType="text/plain; charset=UTF-8"/>
                    </response>
                </method>
            </resource>
        </resource>
        <resource path="/hellorest">
            <method id="sayHello" name="GET">
                <response>
                    <representation mediaType="text/plain"/>
                </response>
            </method>
            <resource path="/{param}">
                <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="param" style="template" type="xs:string"/>
                <method id="sayHelloToUTF8" name="GET">
                    <response>
                        <representation mediaType="text/plain; charset=UTF-8"/>
                    </response>
                </method>
            </resource>
        </resource>
        <resource path="/mail">
            <method id="mailREST" name="GET">
                <request>
                    <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="server" style="query" type="xs:string"/>
                    <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="username" style="query" type="xs:string"/>
                    <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="password" style="query" type="xs:string"/>
                    <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="dbname" style="query" type="xs:string"/>
                    <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="subject" style="query" type="xs:string"/>
                    <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="sendto" style="query" type="xs:string"/>
                    <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="content" style="query" type="xs:string"/>
                    <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="ishtml" style="query" type="xs:string"/>
                </request>
                <response>
                    <representation mediaType="text/plain; charset=UTF-8"/>
                </response>
            </method>
            <resource path="/sendService">
                <method id="crunchifyREST" name="POST">
                    <request>
                        <representation mediaType="application/json"/>
                    </request>
                    <response>
                        <representation mediaType="text/plain; charset=UTF-8"/>
                    </response>
                </method>
            </resource>
        </resource>
        <resource path="device">
            <method id="get" name="GET">
                <request>
                    <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="ip" style="query" type="xs:string"/>
                </request>
                <response>
                    <representation mediaType="application/xml"/>
                    <representation mediaType="application/json"/>
                </response>
            </method>
            <method id="put" name="PUT">
                <response>
                    <representation mediaType="application/xml"/>
                    <representation mediaType="application/json"/>
                </response>
            </method>
        </resource>
        <resource path="UserInfoService">
            <resource path="/name/{i}">
                <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="i" style="template" type="xs:string"/>
                <method id="userName" name="GET">
                    <response>
                        <representation mediaType="text/xml"/>
                    </response>
                </method>
            </resource>
            <resource path="/age/{j}">
                <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="j" style="template" type="xs:int"/>
                <method id="userAge" name="GET">
                    <response>
                        <representation mediaType="text/xml"/>
                    </response>
                </method>
            </resource>
        </resource>
    </resources>
</application>





你可能感兴趣的:(java,Web,REST,web服务,jersey,Services)