Jersey Hello 例子

本文参考:https://www.jianshu.com/p/88f97b90963c

  Jersey RESTful 框架是开源的RESTful框架, 实现了JAX-RS (JSR 311 & JSR 339) 规范。它扩展了JAX-RS 参考实现, 提供了更多的特性和工具, 可以进一步地简化 RESTful service 和 client 开发。

开发环境:eclipse、 Gradle

使用内置容器方式

1 创建 gradle 项目

build.gradle文件引用           

compile 'org.glassfish.jersey.containers:jersey-container-jetty-http:2.29.1'

compile 'org.glassfish.jersey.inject:jersey-hk2:2.29.1'

REST服务类         

package test
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 HelloService {
@GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hi(){
        return "hello jersey";
    }
}

 说明:

        1 包名test,发步服务时要包括此包名

        2 @Path("hello"),代表资源根路径为hello

        3 方法hi上面添加了两个标签,@GET标签代表该方法接受GET类型请求 @Produces标签代表该方法的响应MIME类型为text/plain

        4 该方法返回String,这个String值Jersey会自动按照text/plain格式输出

3 创建一个Application类,用于设置发布环境

package test
import org.glassfish.jersey.server.ResourceConfig;
public class RestApplication extends ResourceConfig{
public RestApplication(){
        this.packages("test");
    }
}

说明:

   在RestApplication类的构造方法中,调用了packages方法注册了扫描资源类的基础包

4 发布应用

import java.net.URI;
import org.glassfish.jersey.jetty.JettyHttpContainerFactory;
public class Test {
public static void main(String[] args) {
   RestApplication restApplication= new RestApplication();
   JettyHttpContainerFactory.createServer(URI.create("http://localhost:8082/"),restApplication);
  }
}

5 客户段测试

  可以通过浏览器或是restclient工具访问 http://localhost:8082/hello

  restclient工具下载网址:windows操作系统下载restclient-ui-fat-版本号.jar

  https://github.com/wiztools/rest-client/releases

  机器上安装jdk环境后,为了方便

  image.png

测试效果

image.png

            

猜你喜欢

转载自blog.51cto.com/14602923/2463966