简体   繁体   English

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

[英]How to embed Jetty and Jersey into my Java application

So I'm trying to embed jetty into my web application so that if I package it as a jar someone can just run the jar file without having to worry about configuring a server. 所以我试图将jetty嵌入到我的Web应用程序中,这样如果我将它打包成jar,就可以运行jar文件而不必担心配置服务器。 However, I'm having some problems setting up my main class so that jetty can access my resource classes. 但是,我在设置主类时遇到了一些问题,因此jetty可以访问我的资源类。 I've looked at tutorials but they haven't given me exactly what I'm looking for. 我看过教程,但他们没有给我我正在寻找的东西。 This is what I have so far. 这就是我到目前为止所拥有的。

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();
    }
}

And I'm trying to map it to this class: 我正在尝试将它映射到这个类:

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);
    }
}

Here's my POM file: 这是我的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>

A few things. 一些东西。

  1. Jetty 9.0.0.RC0 is an old, not-yet stable, release candidate, consider upgrading to a stable, final release, such as 9.0.4.v20130625 Jetty 9.0.0.RC0是一个旧的,尚未稳定的候选版本,考虑升级到稳定的最终版本,例如9.0.4.v20130625
  2. You need something that will connect that Jax RS class into the servlet api. 您需要将Jax RS类连接到servlet api的东西。 Usually done via a Servlet or some sort of initialization with your library of choice. 通常通过Servlet或使用您选择的库进行某种初始化来完成。 (In you case Jersey) (在你的情况下泽西岛)

In your example, you have only setup a DefaultServlet to serve static files, nothing has been configured to use your DBCollection object. 在您的示例中,您只设置了DefaultServlet来提供静态文件,没有任何配置使用您的DBCollection对象。

For Jersey, you'll need to configure the org.glassfish.jersey.servlet.ServletContainer and setup its servlet-mappings on a context of your choice. 对于Jersey,您需要配置org.glassfish.jersey.servlet.ServletContainer并在您选择的上下文中设置其servlet-mappings。

Example: 例:

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);
        }
    }
}

This example adds the ServletContainer that jersey provides to the ServletContextHandler that Jetty uses to look up what to do based on the incoming request. 此示例将jersey提供的ServletContainer添加到Jetlet用于根据传入请求查找要执行的操作的ServletContextHandler。 Then it adds the DefaultServlet to handle any requests for content that Jersey does not handle (such as static content) 然后它添加DefaultServlet来处理Jersey不处理的内容的任何请求(例如静态内容)

In case you want to completely manage the lifecycle of your DBCollection resource programmatically (eg you instantiate it yourself, do some setup/initialization etc), instead of having Jersey create the instance for you, you can use a ResourceConfig like such: 如果您想以编程方式完全管理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();

Note the line TheResource resource = new TheResource(); 注意行TheResource resource = new TheResource(); . Here we create our own instance of TheResource, and we can manipulate it at will now. 在这里,我们创建了自己的TheResource实例,我们现在可以随意操作它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM