Jersey 实现Rest service

  本系列的Jersey主要是快速介绍如何使用Jersey建立RESTful service,记录自己在学习过程中使用或遇到的问题。在最开始会使用轻量级的Grizzly HTTP server发布RESTful service.

1. 使用Mave创建工程
在pom.xml文件中加入如下以来的jar, jersey-server是实现service side的RESTful, jersey-grzzly2是用来发布RESTful的轻量级的server。

package com.study.jersey.server;

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

@Path("helloworld")
public class HelloWorldResource {
    
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHelloWorld(){
        return "Hello World!";
    }
}


2. 开始Server side的开发
1) 使用Annotation编写Root Resource Classes, Root resource Classess实际是一个POJO对象,通过Annotation将其中的方法发布为RESTful service.

package com.study.jersey.server;

import java.io.IOException;
import java.net.URI;

import javax.ws.rs.core.UriBuilder;

import org.glassfish.grizzly.http.server.HttpServer;

import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;

public class PublishService {
    
    public static URI getBaseURI(){
        return UriBuilder.fromUri("http://localhost/").port(9998).build();
    }

    public static final URI BASE_URI = getBaseURI();
    
    protected static HttpServer startServer() throws IllegalArgumentException, NullPointerException, IOException{
        System.out.println("Start server...");
        ResourceConfig config = new PackagesResourceConfig("com.study.jersey.server");
        return GrizzlyServerFactory.createHttpServer(BASE_URI, config);
    }
    public static void main(String[] args) {
        try {
            HttpServer httpServer = startServer();
            System.out.println(String.format("Jersey app started with WADL available at" + "%sapplication.wadl\nTry out %shelloworld\nHit enter to stop it...", BASE_URI, BASE_URI));
            System.in.read();
            httpServer.stop();
        } catch (IllegalArgumentException | NullPointerException | IOException e) {
            e.printStackTrace();
        }
        
    }
}


 

执行上面代码,在console中会提示:

Jersey app started with WADL available athttp: //localhost:9998/application.wadl
Try out http: //localhost:9998/helloworld
Hit enter to stop it...

打开浏览器输入http://localhost:9998/helloworld,可看到返回信息"Hello World!",如果输入 http://localhost:9998/application.wadl,可以看到服务的xml描述. 在这里我们使用Grizzly将服务发布出来。这就实现了第一个简单的RESTful服务。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值