有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

web服务如何在JavaSE环境中部署JAXRS应用程序?

我想用JAX-RS编写一个RESTful web服务,并想在localhost上发布它,比如http://localhost:[port]。我在本报告中读到以下内容:

The Java SE 7 (JSR 336) and the Java SE 8 (JSR 337) specifications don't incorporate the JAX-RS component. However, JAX-RS applications can be published in Java SE environments (using RuntimeDelegate) and JAX-RS implementations also may support publication via JAX-WS.

提到了RuntimeDelegate。我如何使用它?如果有关于如何完成it任务的好例子,请与我分享


共 (1) 个答案

  1. # 1 楼答案

    要在JavaSE环境中部署JAX-RS应用程序,可以使用^{}和JAX-RS实现支持的HTTP服务器。不需要servlet容器

    JSR 339声明如下:

    In a Java SE environment a configured instance of an endpoint class can be obtained using the createEndpoint method of RuntimeDelegate. The application supplies an instance of Application and the type of endpoint required. An implementation MAY support zero or more endpoint types of any desired type.

    How the resulting endpoint class instance is used to publish the application is outside the scope of this specification.

    Jersey是JAX-RS参考实现,它支持range of HTTP servers,您可以使用它在JavaSE中部署JAX-RS应用程序

    例如,使用Grizzly^{},可以获得以下内容:

    public class Example {
    
        public static void main(String[] args) {
    
            ResourceConfig resourceConfig = new ResourceConfig();
            resourceConfig.register(GreetingsResource.class);
    
            HttpHandler handler = RuntimeDelegate.getInstance()
                    .createEndpoint(resourceConfig, HttpHandler.class);
    
            HttpServer server = HttpServer.createSimpleServer(null, 8080);
            server.getServerConfiguration().addHttpHandler(handler);
    
            try {
                server.start();
                System.out.println("Press any key to stop the server...");
                System.in.read();
            } catch (Exception e) {
                System.err.println(e);
            }
        }
    
        @Path("/greetings")
        public static class GreetingsResource {
    
            @GET
            @Produces(MediaType.TEXT_PLAIN)
            public String getGreeting(){
                return "Hello from the other side.";
            }
        }
    }
    

    该应用程序将在http://localhost:8080/greetings上提供

    上述示例需要以下依赖项:

    <dependency>
        <groupId>org.glassfish.grizzly</groupId>
        <artifactId>grizzly-http-server</artifactId>
        <version>2.3.30</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-grizzly2-http</artifactId>
        <version>2.25.1</version>
    </dependency>
    

    其他受支持的实现包括:

    Jersey documentation还描述了不带^{}的JavaSE环境的其他部署替代方案