JAX RS - 嵌入式Jetty和Swagger没有得到json

时间:2016-08-29 02:52:34

标签: jetty swagger

使用以下代码,我可以通过以下方式调用我的API:

http://localhost:8080/test/myapi/squareRoot?input=2

并获取输出

{
    "action":"Square Root",
    "input":2.0,"output":1.4142135623730951
}

但是当我试着打电话时

http://localhost:8080/test/swagger.json

我收到404错误。请帮我理解我的错误。

package com.krish.som.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

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

@Path("myapi")
@Api(value = "/squareRoot", description = "Web Services to browse squareRoot")
public class Calculator {


    @GET
    @Path("squareRoot")
    @ApiOperation(value = "Return one entity", notes = "Returns one entity at random", response = Result.class)
    @Produces(value = MediaType.APPLICATION_JSON)
    public Result squareRoot(@QueryParam("input") double input){
        Result result = new Result("Square Root");
        result.setInput(input);
        result.setOutput(Math.sqrt(result.getInput()));
        return result;
    }

    @GET
    @Path("square")
    @Produces(MediaType.APPLICATION_JSON)
    public Result square(@QueryParam("input") double input){
        Result result = new Result("Square");
        result.setInput(input);
        result.setOutput(result.getInput()*result.getInput());
        return result;
    }

    static class Result{
        double input;
        double output;
        String action;

        public Result(){}

        public Result(String action) {
            this.action = action;
        }

        public String getAction() {
            return action;
        }

        public void setAction(String action) {
            this.action = action;
        }

        public double getInput() {
            return input;
        }

        public void setInput(double input) {
            this.input = input;
        }

        public double getOutput() {
            return output;
        }

        public void setOutput(double output) {
            this.output = output;
        }
    }
}




package com.krish.som.controller;

import com.krish.som.controller.Calculator;
import io.swagger.jaxrs.config.DefaultJaxrsConfig;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.servlet.ServletContainer;

public class SOMServer {
    public SOMServer() {
    }

    public static void main(String[] args) throws Exception {
        Server server = new Server(8080);
        ServletContextHandler context = new ServletContextHandler(1);
        context.setContextPath("/test");
        server.setHandler(context);
        ServletHolder apiServlet = context.addServlet(ServletContainer.class, "/*");
        apiServlet.setInitParameter("jersey.config.server.provider.classnames", Calculator.class.getCanonicalName());
        apiServlet.setInitOrder(0);
        apiServlet.setInitParameter("com.sun.jersey.config.property.packages", "com.krish.som.controller;io.swagger.jaxrs.json;io.swagger.jaxrs.listing;io.swagger.resources");
        ServletHolder swaggerServlet = context.addServlet(DefaultJaxrsConfig.class, "/swagger-core");
        swaggerServlet.setInitOrder(1);
        server.start();
        server.join();
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         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>com.krish</groupId>
    <artifactId>som</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>

        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>


        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>


        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.7</version>
        </dependency>


        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>2.7</version>
        </dependency>


        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jetty-http</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-jersey2-jaxrs</artifactId>
            <version>1.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j-version}</version>
        </dependency>
    </dependencies>

    <properties>
        <slf4j-version>1.7.12</slf4j-version>
    </properties>
</project>

1 个答案:

答案 0 :(得分:0)

您将需要Swagger-UI静态资源到项目的资源文件夹(例如/ webapp)。为此,将其添加到您的Pom.xml

<build>
    <plugins>
     <plugin> 
             <groupId>com.googlecode.maven-download-plugin</groupId> 
             <artifactId>download-maven-plugin</artifactId> 
             <version>1.2.1</version> 
             <executions> 
                 <execution> 
                     <id>swagger-ui</id> 
                     <phase>validate</phase> 
                     <goals> 
                         <goal>wget</goal> 
                     </goals> 
                     <configuration> 
                         <url>https://github.com/swagger-api/swagger-ui/archive/v2.1.1.tar.gz</url> 
                         <unpack>true</unpack> 
                         <outputDirectory>${project.build.directory}</outputDirectory> 
                     </configuration> 
                 </execution> 
             </executions> 
         </plugin> 
        <!-- Load the Swagger-UI components into the src/main/webapp/ directory to enable
        viewing/testing of the API routes. Accessible at http://<host>:<port>/swagger. -->
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.7</version>
            <executions>
                <execution>
                    <id>copy-resources</id>
                    <phase>initialize</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${basedir}/src/main/resources/webapp</outputDirectory>
                        <resources>
                            <resource>
                                <directory>${project.build.directory}/swagger-ui-2.1.1/dist</directory>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

此外,在main方法中,您需要使用default-servlet公开index.html。

swaggerServlet.setInitOrder(1);
...
String resourceBasePath = ServicesRunner.class.getResource("/webapp").toExternalForm();
context.setWelcomeFiles(new String[] {"index.html"});
context.setResourceBase(resourceBasePath);
context.addServlet(new ServletHolder(new DefaultServlet()), "/*");
...
server.start();

免责声明:如果直接添加此代码。您将收到错误java.lang.IllegalStateException: Multiple servlets map to path /*:,我建议使用应用程序上下文路径[ServletContainer.class的路径]作为“ / test”而不是根上下文[此-> context.setContextPath(“ / test” );]。 您还可以将swagger基本路径设置为swaggerServlet.setInitParameter("swagger.api.basepath","http://localhost:8080/test");

要设置JAX-RS,Embedded Jetty和Swagger,请遵循this link

找到sample project相同。