且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

REST Web服务的端点发布

更新时间:2023-09-19 15:32:40

Jersey-Grizzly有一个非常简单的解决方案.来自 https://github.com/jesperfj/jax-rs-heroku :>

Jersey-Grizzly has a very simple solution. From https://github.com/jesperfj/jax-rs-heroku:

package embedded.rest.server;

import java.util.HashMap;
import java.util.Map;

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

import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;

@Path("/hello")
public class Main {

    public static void main(String[] args) {        
        final String baseUri = "http://localhost:7080/";
        final Map<String, String> initParams = new HashMap<String, String>();

        // Register the package that contains your javax.ws.rs-annotated beans here
        initParams.put("com.sun.jersey.config.property.packages","embedded.rest.server");

        System.out.println("Starting grizzly...");
        try {
            SelectorThread threadSelector =
                    GrizzlyWebContainerFactory.create(baseUri, initParams);
            System.out.println(String.format("Jersey started with WADL "
                    + "available at %sapplication.wadl.", baseUri));
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        return "Well, this was easy!";
    }
}

如果您使用的是Maven,则需要以下三个依赖项:

If you're using Maven, you'll need the following three dependencies:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-grizzly</artifactId>
    <version>1.15</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-bundle</artifactId>
    <version>1.15</version>
</dependency>
<dependency>
    <groupId>com.sun.grizzly</groupId>
    <artifactId>grizzly-servlet-webserver</artifactId>
    <version>1.9.18-i</version>
</dependency>

要对其进行测试,只需在浏览器中打开http://localhost:7080/hello.

To test it, just open http://localhost:7080/hello in a browser.