Jersey创建standalone server 二

上一篇文章产生的工程就可立刻开发了。不过看一下pom.xml,什么jersey版本是1.8.太老了。用最新版本吧。

呵呵,下面要折腾一下。

第一,pom.xml要修改一下:

    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-server</artifactId>
      <version>${jersey-version}</version>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-grizzly2</artifactId>
      <version>${jersey-version}</version>
      <scope>compile</scope>
    </dependency>

  <properties>
    <jersey-version>1.15</jersey-version>
  </properties>

第二,Main.java导入的包如下:

import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import java.io.IOException;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.grizzly.http.server.HttpServer;
代码也要做如下修改:

public class Main {

    private static int getPort(int defaultPort) {
        //grab port from environment, otherwise fall back to default port 9998
        String httpPort = System.getProperty("jersey.test.port");
        if (null != httpPort) {
            try {
                return Integer.parseInt(httpPort);
            } catch (NumberFormatException e) {
            }
        }
        return defaultPort;
    }

    private static URI getBaseURI() {
        return UriBuilder.fromUri("http://localhost/").port(getPort(9998)).build();
    }

    public static final URI BASE_URI = getBaseURI();
    
    protected static HttpServer startServer() throws IOException {
	System.out.println("Starting grizzly...");
	ResourceConfig rc = new PackagesResourceConfig("com.esri");
	return GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
	/*
        final Map<String, String> initParams = new HashMap<String, String>();

        initParams.put("com.sun.jersey.config.property.packages", "com.esri");

        System.out.println("Starting grizzly2...");
        return GrizzlyWebContainerFactory.create(BASE_URI, initParams);
	*/
    }
    
    public static void main(String[] args) throws IOException {
        // Grizzly 2 initialization
        HttpServer httpServer = startServer();
        System.out.println(String.format("Jersey app started with WADL available at "
                + "%sapplication.wadl\nHit enter to stop it...",
                BASE_URI));
        System.in.read();
        httpServer.stop();
    }    
}

startServer函数中注释掉的部分是向导产生的旧的代码。

好,再启动看看,一切正常。

你可能感兴趣的:(Jersey创建standalone server 二)