为什么Swagger + REST不能使用@ApplicationPath(“”)

envsm3lx  于 9个月前  发布在  其他
关注(0)|答案(2)|浏览(60)

环境= JBoss 7.2.0.Final + RESTEasy 2.3.5.Final + Swagger 1.3.10
尝试设置一个没有web.xml的WAR并使用Swagger。如果ApplicationPath中有任何值,

@javax.ws.rs.ApplicationPath("test")

@WebServlet(name = "RestEasy-1", loadOnStartup = 1)

@Path("/message")
@Api(value="/message",description="hello api")

适用于URL

http://localhost:8080/RestEasy-1/test/message/xyz (THE SERVICE)
http://localhost:8080/RestEasy-1/test/api-docs (SHOWS SWAGGER JSON)
http://localhost:8080/RestEasy-1/ (RUNS SWAGGER UI)

但是,如果我更改为:

@javax.ws.rs.ApplicationPath("") (also tried /* or * or /)

服务和api-docs工作,但斯瓦格似乎不可用。
我猜这是与servlet根上的侦听器冲突,但我有一个预先存在的约束,即服务在root +路径上运行,因此我需要一个空的ApplicationPath。
任何想法,如果斯瓦格可以设置为运行一个不同的路径手动?

pnwntuvh

pnwntuvh1#

问题是您试图从同一个资源根为应用程序和静态上下文提供服务,这背后存在一些技术问题。
我相信这个SO问题-JAX-RS Application on the root context - how can it be done?-指的是同一件事,并包含了一个广泛的解决问题的方法。

llmtgqce

llmtgqce2#

虽然不能使用@ApplicationPath annotation,但可以使用初始化参数设置应用程序路径:

package org.robferguson.resteasy.examples.fatjar;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;

public class Main {

  static final String APPLICATION_PATH = "/api";
  static final String API_PATH_SPEC = "/api/*";
  static final String SWAGGER_UI_PATH_SPEC = "/*";

  public Main() {}

  public static void main( String[] args ) throws Exception
  {
    try
    {
      new Main().run();
    }
    catch (Throwable t)
    {
      t.printStackTrace();
    }
  }

  public void run() throws Exception
  {
    final int port = 8080;
    final Server server = new Server(port);

    // setup Application context
    ServletContextHandler context = new ServletContextHandler();

    // setup JAX-RS (RESTEasy) resources
    ServletHolder apiServlet = new ServletHolder(
        new HttpServletDispatcher());
    apiServlet.setInitOrder(1);
    apiServlet.setInitParameter("resteasy.servlet.mapping.prefix",
        APPLICATION_PATH);
    apiServlet.setInitParameter("javax.ws.rs.Application",
        "org.robferguson.resteasy.examples.fatjar.FatJarApplication");

    // setup static (Swagger UI) resources
    String resourceBasePath = Main.class.getResource(
      "/swagger-ui").toExternalForm();
    context.setResourceBase(resourceBasePath);
    context.setWelcomeFiles(new String[] { "index.html" });

    ServletHolder swaggerUiServlet = new ServletHolder(
      new DefaultServlet());
    swaggerUiServlet.setInitOrder(2);

    context.addServlet(apiServlet, API_PATH_SPEC);
    context.addServlet(swaggerUiServlet, SWAGGER_UI_PATH_SPEC);

    server.setHandler(context);
    server.start();
    server.join();
  } 
}

查看我的博客了解更多信息:
http://robferguson.org/2016/12/11/resteasy-embedded-jetty-fat-jars-swagger-and-swagger-ui/
我的GitHub repo:
https://github.com/Robinyo/resteasy/tree/master/examples/fatjar-swagger

相关问题