我可以在com.sun.net.httpserver.HttpServer上运行JAX-RS Web服务吗?

时间:2014-06-24 12:22:05

标签: java jax-rs

我可以运行这样的简单网络服务:

@Path("/rs/hello")
public class HelloWorldProgram {

    //path is default
    @GET
    @Produces(MediaType.TEXT_HTML)
    public String sayHello() {
        return "Hello, World!";
    }

    @GET
    @Produces(MediaType.TEXT_XML)
    @Path("/xml")
    public String sayXMLHello() {
        return "<?xml version=\"1.0\"?>" + "<hello> Hello" + "</hello>";
    }
}

与JDK简单Web服务器com.sun.net.httpserver.HttpServer捆绑在一起?

2 个答案:

答案 0 :(得分:2)

是的,你可以。看看&#34; helloworld-pure-jax-rs&#34;泽西的例子:https://github.com/jersey/jersey/tree/master/examples/helloworld-pure-jax-rs

答案 1 :(得分:1)

不,你不能使用com.sun.net.httpserver.HttpServer。您需要一台符合Servlet API的服务器。相反,您可以使用例如org.glassfish.grizzly.http.server.HttpServer:

import java.net.URI;

import javax.ws.rs.core.UriBuilder;

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;

public class Server {

    public static void main(String[] args) throws InterruptedException {
        URI uri = UriBuilder.fromUri("http://localhost/").port(8888).build();
        ResourceConfig rc = new ResourceConfig(HelloWorldProgram.class);
        HttpServer server = GrizzlyHttpServerFactory.createHttpServer(uri, rc);
        Thread.currentThread().join(); // keep running
    }
}

您需要依赖Jersey Container Grizzly2 Servlet