使用Java SE发布REST服务

Raf*_*ael 5 java rest

我正在尝试使用Jersey和/或Java SE内置http服务器,使用JAX-RS 2.0和Java SE发布我的RESTful Web服务的简单方法.

我想将我的依赖关系保持在最低限度,所以我想避免灰熊,也不想使用任何外部应用程序服务器.

你能指点我如何发布有这个要求的休息服务吗?

提前致谢,

我的意思是实现这样的事情:

public static void main(String args[]) {
    try {
        final HttpServer server = GrizzlyHttpServerFactory.createHttpServer("http://localhost:8080/calculator/",new ResourceConfig(SumEndpoint.class));

        System.in.read();
        server.stop();

} catch (IOException ex) {
}
Run Code Online (Sandbox Code Playgroud)

}

......但避免了灰熊依赖

for*_*two 6

如果你只是依赖

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-jdk-http</artifactId>
    <version>2.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

然后,您可以启动服务器

JdkHttpServerFactory.createHttpServer(URI.create("http://localhost:8090/root"),
        new MyApplication());
Run Code Online (Sandbox Code Playgroud)

其中MyApplication扩展ResourceConfig以获取资源扫描.

@ApplicationPath("/")
public class MyApplication extends ResourceConfig {

    public MyApplication() {
        packages("...");
    }
    @GET
    @Produces("text/plain")
    public Response foo() {

        return Response.ok("Hey, it's working!\n").build();
    }
}
Run Code Online (Sandbox Code Playgroud)

可能有更好的方法来控制服务器生命周期,但暂时还没有我这样做.