带 Jersey 或 Resteasy 的嵌入式码头

发布于 2024-12-04 08:53:33 字数 2000 浏览 1 评论 0原文

我想使用带有 JAX-RS 的嵌入式码头(resteasy 或 jersey)来提供 RESTful 服务。 我正在尝试使用 Maven/Eclipse 设置进行创建。 如果我尝试遵循 http://wikis.sun.com/pages/viewpage.action?pageId=21725365 链接我无法解决来自 ServletHolder sh = new ServletHolder(ServletContainer.class); 的错误,

public class Main {

    @Path("/")
    public static class TestResource {

        @GET
        public String get() {
            return "GET";
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        ServletHolder sh = new ServletHolder(ServletContainer.class);

        /*
         * For 0.8 and later the "com.sun.ws.rest" namespace has been renamed to
         * "com.sun.jersey". For 0.7 or early use the commented out code instead
         */
        // sh.setInitParameter("com.sun.ws.rest.config.property.resourceConfigClass",
        // "com.sun.ws.rest.api.core.PackagesResourceConfig");
        // sh.setInitParameter("com.sun.ws.rest.config.property.packages",
        // "jetty");
        sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass",
            "com.sun.jersey.api.core.PackagesResourceConfig");
        sh.setInitParameter("com.sun.jersey.config.property.packages",
            "edu.mit.senseable.livesingapore.platform.restws");
        // sh.setInitParameter("com.sun.jersey.config.property.packages",
        // "jetty");
        Server server = new Server(9999);

        ServletContextHandler context = new ServletContextHandler(server, "/",
            ServletContextHandler.SESSIONS);
        context.addServlet(sh, "/*");
        server.start();
        server.join();
        // Client c = Client.create();
        // WebResource r = c.resource("http://localhost:9999/");
        // System.out.println(r.get(String.class));
        //
        // server.stop();
    }
}

即使这不起作用。 有人能给我建议一些东西/教程/例子吗?

I want make RESTful services using embedded jetty with JAX-RS (either resteasy or jersey).
I am trying to create with maven/eclipse setup.
if I try to follow http://wikis.sun.com/pages/viewpage.action?pageId=21725365 link I am not able to resolve error from ServletHolder sh = new ServletHolder(ServletContainer.class);

public class Main {

    @Path("/")
    public static class TestResource {

        @GET
        public String get() {
            return "GET";
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        ServletHolder sh = new ServletHolder(ServletContainer.class);

        /*
         * For 0.8 and later the "com.sun.ws.rest" namespace has been renamed to
         * "com.sun.jersey". For 0.7 or early use the commented out code instead
         */
        // sh.setInitParameter("com.sun.ws.rest.config.property.resourceConfigClass",
        // "com.sun.ws.rest.api.core.PackagesResourceConfig");
        // sh.setInitParameter("com.sun.ws.rest.config.property.packages",
        // "jetty");
        sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass",
            "com.sun.jersey.api.core.PackagesResourceConfig");
        sh.setInitParameter("com.sun.jersey.config.property.packages",
            "edu.mit.senseable.livesingapore.platform.restws");
        // sh.setInitParameter("com.sun.jersey.config.property.packages",
        // "jetty");
        Server server = new Server(9999);

        ServletContextHandler context = new ServletContextHandler(server, "/",
            ServletContextHandler.SESSIONS);
        context.addServlet(sh, "/*");
        server.start();
        server.join();
        // Client c = Client.create();
        // WebResource r = c.resource("http://localhost:9999/");
        // System.out.println(r.get(String.class));
        //
        // server.stop();
    }
}

even this is not working.
can anyone suggest me something/tutorial/example ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

相思碎 2024-12-11 08:53:33

呵呵,链接页面很古老 - 最后更新是在 3 年前。

你真的需要码头吗? Jersey 与 Grizzly(参见 http://grizzly.java.net)进行了出色的彻底测试集成,Grizzly 也充当 Glassfish 传输层,并且它可以像您的示例中那样使用它。

请参阅 Jersey 工作区中的 helloworld 示例,com.sun.jersey.samples.helloworld.Main 类启动 Grizzly 并“部署”helloworld 应用程序:http://repo1.maven.org/ maven2/com/sun/jersey/samples/helloworld/1.9.1/helloworld-1.9.1-project.zip

如果您确实需要基于码头的样品,我想我应该能够提供(请随时与我联系)。

编辑:

好的,如果你真的想要码头,你可以拥有它:)并且看起来它相当简单。我按照 http://docs.codehaus.org/display/JETTY/Embedding+Jetty 的说明进行操作能够启动 helloworld 示例:

public static void main(String[] args) throws Exception {
    Server server = new Server(8080);
    Context root = new Context(server,"/",Context.SESSIONS);
    root.addServlet(new ServletHolder(new ServletContainer(new PackagesResourceConfig("com.sun.jersey.samples.helloworld"))), "/");
    server.start();
}

http://localhost:8080/helloworld 可以访问。我使用的是 Jetty 6.1.16。希望有帮助!

您可以在用户指南中找到有关在 servlet 环境中配置 Jersey 的更多信息,请参阅 http://jersey.java.net/nonav /documentation/latest/

编辑:

依赖关系..但这有点难以指定,它最近在泽西岛发生了变化..所以..

pre 1.10:

<dependency>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>jetty</artifactId>
    <version>6.1.16</version>
</dependency>
<dependency>
     <groupId>com.sun.jersey</groupId>
     <artifactId>jersey-server</artifactId>
     <version>${jersey.version}</version>
</dependency>

post 1.10:

<dependency>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>jetty</artifactId>
    <version>6.1.16</version>
</dependency>
<dependency>
     <groupId>com.sun.jersey</groupId>
     <artifactId>jersey-servlet</artifactId>
     <version>${jersey.version}</version>
</dependency>

你需要这个maven repo码头:

<repositories>
    <repository>
        <id>codehaus-release-repo</id>
        <name>Codehaus Release Repo</name>
        <url>http://repository.codehaus.org</url>
    </repository>
</repositories>

huh, linked page is ancient - last update 3 years ago.

Do you really need jetty? Jersey has excellent thoroughly tested integration with Grizzly (see http://grizzly.java.net) which is also acting as Glassfish transport layer and it is possible to use it as in your example.

See helloworld sample from Jersey workspace, com.sun.jersey.samples.helloworld.Main class starts Grizzly and "deploys" helloworld app: http://repo1.maven.org/maven2/com/sun/jersey/samples/helloworld/1.9.1/helloworld-1.9.1-project.zip .

If you really need jetty based sample, I guess I should be able to provide it (feel free to contact me).

EDIT:

ok, if you really want jetty, you can have it :) and looks like its fairly simple. I followed instructions from http://docs.codehaus.org/display/JETTY/Embedding+Jetty and was able to start helloworld sample:

public static void main(String[] args) throws Exception {
    Server server = new Server(8080);
    Context root = new Context(server,"/",Context.SESSIONS);
    root.addServlet(new ServletHolder(new ServletContainer(new PackagesResourceConfig("com.sun.jersey.samples.helloworld"))), "/");
    server.start();
}

http://localhost:8080/helloworld is accessible. I used Jetty 6.1.16. Hope it helps!

You can find more information about configuring Jersey in servlet environment in user guide, see http://jersey.java.net/nonav/documentation/latest/

EDIT:

dependencies.. but this is kind of hard to specify, it changed recently in jersey.. so..

pre 1.10:

<dependency>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>jetty</artifactId>
    <version>6.1.16</version>
</dependency>
<dependency>
     <groupId>com.sun.jersey</groupId>
     <artifactId>jersey-server</artifactId>
     <version>${jersey.version}</version>
</dependency>

post 1.10:

<dependency>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>jetty</artifactId>
    <version>6.1.16</version>
</dependency>
<dependency>
     <groupId>com.sun.jersey</groupId>
     <artifactId>jersey-servlet</artifactId>
     <version>${jersey.version}</version>
</dependency>

and you need this maven repo for jetty:

<repositories>
    <repository>
        <id>codehaus-release-repo</id>
        <name>Codehaus Release Repo</name>
        <url>http://repository.codehaus.org</url>
    </repository>
</repositories>
大海や 2024-12-11 08:53:33

这是一个 github 存储库,其中包含为 master 分支上的 Grizzly 和“jetty”分支上的 Jetty 配置的基于 Maven 的 HelloWorld 示例:

https://github.com/jesperfj/jax-rs-heroku

尽管存储库名称如此,但它并不是 Heroku 特定的。通过运行 Procfile 中指定的命令来启动服务器,例如

$ java -cp "target/dependency/*":target/classes Main

Here's a github repo with a Maven based HelloWorld sample configured for Grizzly on master branch and for Jetty on "jetty" branch:

https://github.com/jesperfj/jax-rs-heroku

Despite the repo name it's not Heroku specific. Start the server by running the command specified in Procfile, e.g.

$ java -cp "target/dependency/*":target/classes Main
成熟的代价 2024-12-11 08:53:33

嵌入式jetty,带有reaseasy,无需web.xml

java代码:

    final QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMinThreads(2); // 10
    threadPool.setMaxThreads(8); // 200
    threadPool.setDetailedDump(false);
    threadPool.setName(SERVER_THREAD_POOL);
    threadPool.setDaemon(true);

    final SelectChannelConnector connector = new SelectChannelConnector();
    connector.setHost(HOST);
    connector.setAcceptors(2);
    connector.setPort(PROXY_SEVLET_PORT);
    connector.setMaxIdleTime(MAX_IDLE_TIME);
    connector.setStatsOn(false);
    connector.setLowResourcesConnections(LOW_RESOURCES_CONNECTIONS);
    connector.setLowResourcesMaxIdleTime(LOW_RESOURCES_MAX_IDLE_TIME);
    connector.setName(HTTP_CONNECTOR_NAME);            

    /* Setup ServletContextHandler */
    final ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
    contextHandler.setContextPath("/");
    contextHandler.addEventListener(new ProxyContextListener());

    contextHandler.setInitParameter("resteasy.servlet.mapping.prefix","/services");

    final ServletHolder restEasyServletHolder = new ServletHolder(new HttpServletDispatcher());
    restEasyServletHolder.setInitOrder(1);

/* Scan package for web services*/
restEasyServletHolder.setInitParameter("javax.ws.rs.Application","com.viacom.pl.cprox.MessageApplication");

    contextHandler.addServlet(restEasyServletHolder, "/services/*");

    final HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { contextHandler });

    final Server server = new Server();
    server.setThreadPool(threadPool);
    server.setConnectors(new Connector[] { connector });
    server.setHandler(handlers);
    server.setStopAtShutdown(true);
    server.setSendServerVersion(true);
    server.setSendDateHeader(true);
    server.setGracefulShutdown(1000);
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);

    server.start();
    server.join();

Web服务检测器:

package com.viacom.pl.cprox;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;

import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.viacom.pl.cprox.services.impl.AbstractWebServiceMethod;

public class MessageApplication extends Application {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageApplication.class);

    private Set<Object> singletons = new HashSet<Object>();

    @SuppressWarnings("rawtypes")
    public MessageApplication() {

        /* Setup RestEasy */
        Reflections reflections = new Reflections("com.viacom.pl.cprox.services.impl");

        /*All my web services methods wrapper class extends AbstractWebServiceMethod, so it is easy to get sub set of expected result.*/
        Set<Class<? extends AbstractWebServiceMethod>> set = reflections
                .getSubTypesOf(AbstractWebServiceMethod.class);
        for (Class<? extends AbstractWebServiceMethod> clazz : set) {
            try {
                singletons.add(clazz.newInstance());
            } catch (InstantiationException e) {
                LOGGER.error(e.getMessage(), e);
            } catch (IllegalAccessException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

pom.xml

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxb-provider</artifactId>
    <version>2.2.0.GA</version>
</dependency>
<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.9-RC1</version>
</dependency>

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>3.0.3.Final</version>
</dependency>

Embedded jetty with reaseasy without web.xml

java code:

    final QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMinThreads(2); // 10
    threadPool.setMaxThreads(8); // 200
    threadPool.setDetailedDump(false);
    threadPool.setName(SERVER_THREAD_POOL);
    threadPool.setDaemon(true);

    final SelectChannelConnector connector = new SelectChannelConnector();
    connector.setHost(HOST);
    connector.setAcceptors(2);
    connector.setPort(PROXY_SEVLET_PORT);
    connector.setMaxIdleTime(MAX_IDLE_TIME);
    connector.setStatsOn(false);
    connector.setLowResourcesConnections(LOW_RESOURCES_CONNECTIONS);
    connector.setLowResourcesMaxIdleTime(LOW_RESOURCES_MAX_IDLE_TIME);
    connector.setName(HTTP_CONNECTOR_NAME);            

    /* Setup ServletContextHandler */
    final ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
    contextHandler.setContextPath("/");
    contextHandler.addEventListener(new ProxyContextListener());

    contextHandler.setInitParameter("resteasy.servlet.mapping.prefix","/services");

    final ServletHolder restEasyServletHolder = new ServletHolder(new HttpServletDispatcher());
    restEasyServletHolder.setInitOrder(1);

/* Scan package for web services*/
restEasyServletHolder.setInitParameter("javax.ws.rs.Application","com.viacom.pl.cprox.MessageApplication");

    contextHandler.addServlet(restEasyServletHolder, "/services/*");

    final HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { contextHandler });

    final Server server = new Server();
    server.setThreadPool(threadPool);
    server.setConnectors(new Connector[] { connector });
    server.setHandler(handlers);
    server.setStopAtShutdown(true);
    server.setSendServerVersion(true);
    server.setSendDateHeader(true);
    server.setGracefulShutdown(1000);
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);

    server.start();
    server.join();

Web services detector:

package com.viacom.pl.cprox;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;

import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.viacom.pl.cprox.services.impl.AbstractWebServiceMethod;

public class MessageApplication extends Application {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageApplication.class);

    private Set<Object> singletons = new HashSet<Object>();

    @SuppressWarnings("rawtypes")
    public MessageApplication() {

        /* Setup RestEasy */
        Reflections reflections = new Reflections("com.viacom.pl.cprox.services.impl");

        /*All my web services methods wrapper class extends AbstractWebServiceMethod, so it is easy to get sub set of expected result.*/
        Set<Class<? extends AbstractWebServiceMethod>> set = reflections
                .getSubTypesOf(AbstractWebServiceMethod.class);
        for (Class<? extends AbstractWebServiceMethod> clazz : set) {
            try {
                singletons.add(clazz.newInstance());
            } catch (InstantiationException e) {
                LOGGER.error(e.getMessage(), e);
            } catch (IllegalAccessException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

pom.xml

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxb-provider</artifactId>
    <version>2.2.0.GA</version>
</dependency>
<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.9-RC1</version>
</dependency>

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>3.0.3.Final</version>
</dependency>
舂唻埖巳落 2024-12-11 08:53:33

我能够在半小时内启动并运行这个 Maven 原型。

请参阅 https://github.com/cb372/jersey-jetty-guice-archetype

步骤:

git clone https://github.com/cb372/jersey-jetty-guice-archetype.git
mvn install
mvn archetype:generate -DarchetypeGroupId=org.birchall \
    -DarchetypeArtifactId=jersey-jetty-guice-archetype -DarchetypeVersion=1.0
mvn compile exec:java -Dexec.mainClass=com.yourpackage.Main

非常感谢 cb372 创建这个原型。它让事情变得如此简单。

I was able to get this maven archetype up and running in half an hour.

See https://github.com/cb372/jersey-jetty-guice-archetype

Steps:

git clone https://github.com/cb372/jersey-jetty-guice-archetype.git
mvn install
mvn archetype:generate -DarchetypeGroupId=org.birchall \
    -DarchetypeArtifactId=jersey-jetty-guice-archetype -DarchetypeVersion=1.0
mvn compile exec:java -Dexec.mainClass=com.yourpackage.Main

Huge thanks to cb372 for creating this archetype. It makes it so easy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文