如何将Jetty和Jersey嵌入到我的Java应用程序中

时间:2013-07-30 17:47:44

标签: java maven jetty embedded-jetty

所以我试图将jetty嵌入到我的Web应用程序中,这样如果我把它打包成jar,就可以运行jar文件而不必担心配置服务器。但是,我在设置主类时遇到了一些问题,因此jetty可以访问我的资源类。我看过教程,但他们没有给我我正在寻找的东西。这就是我到目前为止所拥有的。

package pojo;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class Main {

    public static void main(String[] args) throws Exception {
        Server server = new Server(8080);
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
        context.setContextPath("/");
        ServletHolder h = new ServletHolder(new DefaultServlet());
        h.setInitParameter("javax.ws.rs.Application","resources.DBCollection");
        context.addServlet(h, "/*");
        server.setHandler(context);
        server.start();
        server.join();
    }
}

我正在尝试将它映射到这个类:

package resources;


import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;

import pojo.Party;

@Path("/parties")
public class DBCollection {

    @Context
    UriInfo url;

    @Context
    Request request;

    String name;

    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public List<Party> getAllParties() throws Exception
    {
        List<Party> list = new ArrayList<Party>();
        list.addAll(DBConnection.getPartyCollection().values());
        return list;
    }

    @GET
    @Path("count")
    @Produces(MediaType.TEXT_PLAIN)
    public String getPartyCount() throws Exception
    {
        return String.valueOf(DBConnection.getPartyCollection().size());
    }

    @Path("{party}")
    public DBResource getParty(@PathParam("party")String party)
    {
        return new DBResource(url,request,party);
    }
}

这是我的POM文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>PartyAPI</groupId>
    <artifactId>PartyAPIMaven</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>com.codahale.metrics</groupId>
            <artifactId>metrics-core</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.17.1</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.0.0.RC0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>9.0.0.RC0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlets</artifactId>
            <version>9.0.0.RC0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.6.0-SNAPSHOT</version>
        </dependency>

    </dependencies>
    <repositories>
        <repository>
            <id>oss.sonatype.org</id>
            <name>OSS Sonatype Staging</name>
            <url>https://oss.sonatype.org/content/groups/staging</url>
        </repository>
    </repositories>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>1.6</version>
                <configuration>
                    <createDependencyReducedPom>true</createDependencyReducedPom>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                            </excludes>
                        </filter>
                    </filters>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <manifestEntries>
                                        <Main-Class>com.resteasy.Star.Main</Main-Class>

                                    </manifestEntries>

                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

2 个答案:

答案 0 :(得分:19)

一些事情。

  1. Jetty 9.0.0.RC0是一个旧的,尚未稳定的候选版本,考虑升级到稳定的最终版本,例如9.0.4.v20130625
  2. 您需要将Jax RS类连接到servlet api的东西。通常通过Servlet或使用您选择的库进行某种初始化来完成。 (在你的情况下泽西岛)
  3. 在您的示例中,您只设置DefaultServlet来提供静态文件,没有配置任何内容来使用您的DBCollection对象。

    对于Jersey,您需要配置org.glassfish.jersey.servlet.ServletContainer并在您选择的上下文中设置其servlet-mappings。

    示例:

    package com.example;
    
    import org.eclipse.jetty.server.Server;
    import org.eclipse.jetty.servlet.DefaultServlet;
    import org.eclipse.jetty.servlet.ServletContextHandler;
    import org.eclipse.jetty.servlet.ServletHolder;
    
    public class Main
    {
        public static void main(String[] args)
        {
            Server server = new Server(8080);
    
            ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
            context.setContextPath("/");
            server.setHandler(context);
    
            ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/webapi/*");
            jerseyServlet.setInitOrder(1);
            jerseyServlet.setInitParameter("jersey.config.server.provider.packages","com.example");
    
            ServletHolder staticServlet = context.addServlet(DefaultServlet.class,"/*");
            staticServlet.setInitParameter("resourceBase","src/main/webapp");
            staticServlet.setInitParameter("pathInfoOnly","true");
    
            try
            {
                server.start();
                server.join();
            }
            catch (Throwable t)
            {
                t.printStackTrace(System.err);
            }
        }
    }
    

    此示例将jersey提供的ServletContainer添加到Jetlet用于根据传入请求查找要执行的操作的ServletContextHandler。然后它添加DefaultServlet来处理Jersey不处理的内容的任何请求(例如静态内容)

答案 1 :(得分:10)

如果您想以编程方式完全管理DBCollection资源的生命周期(例如,您自己实例化,进行一些设置/初始化等),而不是让Jersey为您创建实例,您可以使用ResourceConfig喜欢这样:

ServletContextHandler sch = new ServletContextHandler();
sch.setContextPath("/xxx");

TheResource resource = new TheResource();
ResourceConfig rc = new ResourceConfig();
rc.register(resource);

ServletContainer sc = new ServletContainer(rc);
ServletHolder holder = new ServletHolder(sc);
sch.addServlet(holder, "/*");

Server server = new Server(port);
server.setHandler(sch);
server.start();
server.join();

注意第TheResource resource = new TheResource();行。在这里,我们创建了自己的TheResource实例,我们现在可以随意操作它。