java 如何在不使用 tomcat 的情况下运行 jersey-server webservice 服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31992461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:29:04  来源:igfitidea点击:

How to run jersey-server webservice server without using tomcat

javaweb-servicesrestmavenjersey

提问by zwlayer

This is my first time dealing with web-services. Simply, I need to send a post request from jersey web service client (inside a webpage implemented in javascript) to a jersey service which is in one of my maven modules.

这是我第一次处理网络服务。简单地说,我需要将来自 jersey Web 服务客户端(在 javascript 中实现的网页内)的 post 请求发送到我的 maven 模块之一中的 jersey 服务。

As I said I've created jersey-server within one of my maven modules and I would like to run it somehow (I do not know how to run a web service program.) before starting client side of my implementation. Through searching on the web, I saw lots of examples but all of them was using tomcat. So my first question is that do I need to use tomcat (or something like this ) in order to run a web service ? Secondly, below I shared my jersey-server module. How could I start to run it ?

正如我所说,我已经在我的一个 maven 模块中创建了 jersey-server,我想在开始我的实现的客户端之前以某种方式运行它(我不知道如何运行 Web 服务程序。)。在网上搜索,看到很多例子,但都是使用tomcat的。所以我的第一个问题是我是否需要使用 tomcat(或类似的东西)才能运行 Web 服务?其次,下面我分享了我的 jersey-server 模块。我怎么能开始运行它?

package com.exampleProject.rest;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;


@Path("/test")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class SiderRecommender {

    @POST
    @Path("/functiontest")
    public List<Recommendation> sampleFunction() {
        // return something here. I removed it for simplicity.
    }
}

回答by Paul Samsotha

You don't haveto run a Jersey app in an installed web server. You can run it in an embeddedserver, meaning a server that runs in standalone mode with a normal mainmethod.

你不具备在已安装的Web服务器运行一个应用程序新泽西州。您可以在嵌入式服务器中运行它,这意味着在独立模式下使用正常main方法运行的服务器。

If you are using Maven, and you are familiar with creating Maven archetypes, you can use the jersey-quickstart-grizzly2archetype

如果您正在使用 Maven,并且您熟悉创建 Maven 原型,则可以使用jersey-quickstart-grizzly2原型

This is everything you get for free with the archetype project.

这是您通过原型项目免费获得的一切。

enter image description here

在此处输入图片说明

Main.java

Main.java

package com.underdog.jersey.grizzly;

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;

import java.io.IOException;
import java.net.URI;

/**
 * Main class.
 *
 */
public class Main {
    // Base URI the Grizzly HTTP server will listen on
    public static final String BASE_URI = "http://localhost:8080/myapp/";

    /**
     * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
     * @return Grizzly HTTP server.
     */
    public static HttpServer startServer() {
        // create a resource config that scans for JAX-RS resources and providers
        // in com.underdog.jersey.grizzly package
        final ResourceConfig rc = new ResourceConfig().packages("com.underdog.jersey.grizzly");

        // create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
    }

    /**
     * Main method.
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        final HttpServer server = 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();
        server.stop();
    }
}

MyResource.java

MyResource.java

package com.underdog.jersey.grizzly;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 * Root resource (exposed at "myresource" path)
 */
@Path("myresource")
public class MyResource {

    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "text/plain" media type.
     *
     * @return String that will be returned as a text/plain response.
     */
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt() {
        return "Got it!";
    }
}

MyResourceTest.java

MyResourceTest.java

package com.underdog.jersey.grizzly;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;

import org.glassfish.grizzly.http.server.HttpServer;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class MyResourceTest {

    private HttpServer server;
    private WebTarget target;

    @Before
    public void setUp() throws Exception {
        // start the server
        server = Main.startServer();
        // create the client
        Client c = ClientBuilder.newClient();

        // uncomment the following line if you want to enable
        // support for JSON in the client (you also have to uncomment
        // dependency on jersey-media-json module in pom.xml and Main.startServer())
        // --
        // c.configuration().enable(new org.glassfish.jersey.media.json.JsonJaxbFeature());

        target = c.target(Main.BASE_URI);
    }

    @After
    public void tearDown() throws Exception {
        server.stop();
    }

    /**
     * Test to see that the message "Got it!" is sent in the response.
     */
    @Test
    public void testGetIt() {
        String responseMsg = target.path("myresource").request().get(String.class);
        assertEquals("Got it!", responseMsg);
    }
}

pom.xml- I added the jersey-media-json-Hymansonand the maven-assembly-pluginmyself, so that you can create a single runnable jar file.

pom.xml- 我添加了jersey-media-json-Hymansonmaven-assembly-plugin我自己,以便您可以创建一个可运行的 jar 文件。

<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/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.underdog</groupId>
    <artifactId>jersey-grizzly</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>jersey-grizzly</name>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-http</artifactId>
        </dependency>
         <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-Hymanson</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.5.3</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>com.underdog.jersey.grizzly.Main</mainClass>
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>create-archive</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>java</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <mainClass>com.underdog.jersey.grizzly.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <jersey.version>2.17</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

With all the above, you can cdto the project from the command line and do

有了以上所有内容,您就可以cd从命令行进入项目并执行

  1. mvn clean package
  2. java -jar target/jersey-grizzly-jar-with-dependencies.jar
  1. mvn clean package
  2. java -jar target/jersey-grizzly-jar-with-dependencies.jar

and the application will start.

应用程序将启动。

You can access it from http://localhost:8080/myapp/myresource

您可以从 http://localhost:8080/myapp/myresource

That's it. Note that the above is a normal jar project. So if you can't follow how to create the archetype, you can pretty much copy everything above into a jar project.

而已。注意上面是一个普通的jar项目。所以如果你不能遵循如何创建原型,你几乎可以将上面的所有内容复制到一个 jar 项目中。

See Also:

也可以看看:

回答by ihappyk

Since your using Maven, hence you need to configure the properties to run on the Tomcat.RUN Configuration

由于您使用 Maven,因此您需要配置要在 Tomcat 上运行的属性。运行配置

Right click on the Project -> Run as-> Run Configuration Select the Maven Tomcat-> change the goals to 'tomcat:run'

右键单击项目-> 运行方式-> 运行配置选择Maven Tomcat-> 将目标更改为'tomcat:run'

回答by BlogSuperior.com

I can't comment the first answer. So I'm adding a comment here. If you choose to generate the project with the archetype, the command line should be

我无法评论第一个答案。所以我在这里添加评论。如果选择使用原型生成项目,则命令行应为

mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-grizzly2 -DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false -DgroupId=com.underdog.jersey.grizzly -DartifactId=simple-service -Dpackage=com.underdog.jersey.grizzly -DarchetypeVersion=2.23.1

And not the command line in the link. This will work with the pom provided by peeskillet

而不是链接中的命令行。这将适用于 peeskillet 提供的 pom