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

2022-09-03 05:07:09

因此,我正在尝试将jetty嵌入到我的Web应用程序中,以便如果我将其打包为jar,则有人可以运行jar文件,而不必担心配置服务器。但是,我在设置主类以便码头可以访问我的资源类时遇到了一些问题。我已经看过教程,但他们并没有给我确切的要求。这就是我到目前为止所拥有的。

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>

答案 1

一些事情。

  1. Jetty 9.0.0.RC0 是一个旧的、尚未稳定的候选版本,请考虑升级到稳定的最终版本,例如 9.0.4.v20130625
  2. 你需要一些东西来将Jax RS类连接到servlet api中。通常通过Servlet或使用您选择的库进行某种初始化来完成。(在你的情况下泽西岛)

在您的示例中,您只设置了 a 来提供静态文件,没有任何东西被配置为使用您的对象。DefaultServletDBCollection

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

例:

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

此示例将球衣提供的 ServletContainer 添加到 ServletContextHandler,Jetty 使用该 ServletContextHandler 根据传入的请求查找要执行的操作。然后,它添加 DefaultServlet 来处理对 Jersey 未处理的内容(如静态内容)的任何请求


答案 2

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

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实例,现在我们可以随意操作它。TheResource resource = new TheResource();


推荐