restfull webservice

转自http://www.vogella.com/tutorials/REST/article.html


Create your first RESTful Webservice

6.1. Create a new Gradle project and configure jersey usage and Eclipse WTP

Create a new Gradle project named com.vogella.jersey.first with com.vogella.jersey.first as the top-level package name and configure Eclipse WTP. You can follow Required setup for Gradle and Eclipse web projects to get started.

To import the Jersey dependencies, add the following dependency to your build.gradle file.

compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.25.1'

6.2. Java Class

Create the following class.

package com.vogella.jersey.first;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

// Plain old Java Object it does not extend as class or implements
// an interface

// The class registers its methods for the HTTP GET request using the @GET annotation.
// Using the @Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML.

// The browser requests per default the HTML MIME type.

//Sets the path to base URL + /hello
@Path("/hello")
public class Hello {

  // This method is called if TEXT_PLAIN is request
  @GET
  @Produces(MediaType.TEXT_PLAIN)
  public String sayPlainTextHello() {
    return "Hello Jersey";
  }

  // This method is called if XML is request
  @GET
  @Produces(MediaType.TEXT_XML)
  public String sayXMLHello() {
    return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
  }

  // This method is called if HTML is request
  @GET
  @Produces(MediaType.TEXT_HTML)
  public String sayHtmlHello() {
    return "<html> " + "<title>" + "Hello Jersey" + "</title>"
        + "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
  }

}

This class register itself as a get resource via the @GET annotation. Via the @Produces annotation it defines that it delivers the text and the HTML MIME types. It also defines via the @Path annotation that its service is available under the hello URL.

The browser will always request the HTML MIME type. To see the text version, you can use tool like curl.

6.3. Define Jersey Servlet dispatcher

You need to register Jersey as the servlet dispatcher for REST requests.

Open the file web.xml and modify it to the following.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>com.vogella.jersey.first</display-name>
 <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
     <!-- Register resources and providers under com.vogella.jersey.first package. -->
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.vogella.jersey.first</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

The parameter jersey.config.server.provider.packages defines in which package Jersey will look for the web service classes. This property must point to your resources classes. The URL pattern defines the part of the base URL your application will be placed.

6.4. Run your rest service

To run your web application in Eclipse, make sure to run the gradle task eclipseWtp first. Afterwards, you should be able to run the application by right click on the projects name ▸ Run As ▸ Run on Server

You should be able to access your resources under the following URL:

http://localhost:8080/com.vogella.jersey.first/rest/hello
Result of the Jersey service

This URL is derived from the context root value in the projects properties Web Project Settings (by default, this is your application name), augmented with the servlet-mapping URL-pattern and the hello @Path annotation from your class file. You should get the message "Hello Jersey".

As we are using Gradle, if you want to update the context root include the following in your build.gradle and update your web container (right click on server ▸ Publish in the Servers Eclipse View).

eclipse {
    wtp {
        component {
            contextPath = 'newName'
        }
    }
}

The browser requests the HTML representation of your resource. In the next chapter we are going to write a client which will read the XML representation.

7. Create a REST client

Jersey contains a REST client library which can be used for testing or to build a real client in Java. The usage of this library is demonstrated in the following tutorial.

Create a new Java gradle project with com.vogella.jersey.first.client as top-level package name and add following dependency to your build.gradle file to import the Jersey dependencies.

compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.25.1'

Create the following test class.

package com.vogella.jersey.first.client;

import java.net.URI;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;

import org.glassfish.jersey.client.ClientConfig;

public class Test {

    public static void main(String[] args) {
        ClientConfig config = new ClientConfig();

        Client client = ClientBuilder.newClient(config);

        WebTarget target = client.target(getBaseURI());

        String response = target.path("rest").
                            path("hello").
                            request().
                            accept(MediaType.TEXT_PLAIN).
                            get(Response.class)
                            .toString();


        String plainAnswer =
                target.path("rest").path("hello").request().accept(MediaType.TEXT_PLAIN).get(String.class);
        String xmlAnswer =
                target.path("rest").path("hello").request().accept(MediaType.TEXT_XML).get(String.class);
        String htmlAnswer=
                target.path("rest").path("hello").request().accept(MediaType.TEXT_HTML).get(String.class);

        System.out.println(response);
        System.out.println(plainAnswer);
        System.out.println(xmlAnswer);
        System.out.println(htmlAnswer);
    }

    private static URI getBaseURI() {
        return UriBuilder.fromUri("http://localhost:8080/com.vogella.jersey.first").build();
    }
}
其它参考http://www.cnblogs.com/Mr-kevin/p/5806928.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值