以编程方式将servlet添加到嵌入式灰熊中

时间:2014-06-30 12:00:03

标签: servlets jersey swagger grizzly

我正在尝试将Swagger集成到运行嵌入式灰熊服务器的Java SE应用程序中。

为了解决这个问题,我正在关注这个tutorial,我很害羞,我90%在那里。

我想使用此servlet配置swagger:

@WebServlet(name = "SwaggerJaxrsConfig", loadOnStartup = 1)
public class SwaggerJaxrsConfig extends HttpServlet {

    @Override
    public void init(ServletConfig servletConfig) {
        try {
            super.init(servletConfig);
            System.out.println("Swagger init");
            SwaggerConfig swaggerConfig = new SwaggerConfig();
            ConfigFactory.setConfig(swaggerConfig);
            swaggerConfig.setBasePath("http://localhost:8082/swagger4javaee-web/rest");
            swaggerConfig.setApiVersion("1.0.0");
            ScannerFactory.setScanner(new DefaultJaxrsScanner());
            ClassReaders.setReader(new DefaultJaxrsApiReader());
        } catch (ServletException e) {
            System.out.println(e.getMessage());
        }
    }
}

由于我正在使用嵌入式服务器,因此@WebServlet注释不会将servlet添加到grizzly服务器。

有人知道如何以编程方式将servlet添加到grizzly服务器吗?

PS我正在使用此依赖

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-servlet</artifactId>
    <version>2.9</version>
</dependency>

1 个答案:

答案 0 :(得分:5)

以下适用于我。我希望它也适合你。

<强> Main.java

import com.wordnik.swagger.jaxrs.config.BeanConfig;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.ext.ContextResolver;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.moxy.json.MoxyJsonConfig;
import org.glassfish.jersey.server.ResourceConfig;

public class Main {

    private static final URI BASE_URI
            = URI.create("http://localhost:8080/api/");

    public static void main(String[] args) {
        try {
            BeanConfig beanConfig = new BeanConfig();
            beanConfig.setVersion("1.0");
            beanConfig.setScan(true);
            beanConfig.setResourcePackage(
                    HelloResource.class.getPackage().getName());
            beanConfig.setBasePath(BASE_URI.toString());
            beanConfig.setDescription("Hello resources");
            beanConfig.setTitle("Hello API");

            final HttpServer server
                    = GrizzlyHttpServerFactory.createHttpServer(
                            BASE_URI, createApp());

            System.out.println(
                    String.format(
                            "Application started.%nHit enter to stop it..."));
            System.in.read();
            server.shutdownNow();
            System.exit(0);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static ResourceConfig createApp() {
        return new ResourceConfig().
                packages(HelloResource.class.getPackage().getName(),
                        "com.wordnik.swagger.jaxrs.listing").
                register(createMoxyJsonResolver());
    }

    public static ContextResolver<MoxyJsonConfig> createMoxyJsonResolver() {
        final MoxyJsonConfig moxyJsonConfig = new MoxyJsonConfig();
        Map<String, String> namespacePrefixMapper
                = new HashMap<String, String>(1);
        namespacePrefixMapper.put(
                "http://www.w3.org/2001/XMLSchema-instance", "xsi");
        moxyJsonConfig.setNamespacePrefixMapper(namespacePrefixMapper)
                .setNamespaceSeparator(':');
        return moxyJsonConfig.resolver();
    }

}

<强> HelloResource.java

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("hello")
@Api(value = "/hello", description = "Say Hello!")
public class HelloResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Say Hello World",
            notes = "Anything Else?")
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(code = 500, message = "Something wrong in Server")})
    public Response sayHello() {
        JsonObject value = Json.createObjectBuilder()
                .add("firstName", "Jeremy")
                .add("lastName", "Chung")
                .add("message", "Hello World!")
                .build();
        return Response.status(200).entity(value).build();
    }
}

Maven pom.xml 包含以下依赖项。

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-servlet</artifactId>
    <version>2.9</version>
</dependency>
<dependency>
    <groupId>com.wordnik</groupId>
    <artifactId>swagger-jaxrs_2.10</artifactId>
    <version>1.3.1</version>
</dependency>  
<dependency>
    <groupId>com.wordnik</groupId>
    <artifactId>swagger-jersey-jaxrs_2.10</artifactId>
    <version>1.3.0</version>
</dependency>
<dependency>  
    <groupId>org.glassfish</groupId> 
    <artifactId>javax.json</artifactId> 
    <version>1.0.4</version> 
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.10.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-processing</artifactId>
    <version>2.10</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.17.1</version>
</dependency>   

调用http://localhost:8080/api/hello会导致:

  

{“firstName”:“Jeremy”,“lastName”:“Chung”,“message”:“Hello World!”}

调用http://localhost:8080/api/api-docs会导致:

  

{ “apiVersion”: “1.0”, “swaggerVersion”: “1.2”, “的API”:[{ “路径”: “/你好”, “说明”:“喂   你好!“}]}

调用http://localhost:8080/api/api-docs/hello会导致:

{"apiVersion":"1.0","swaggerVersion":"1.2","basePath":"http://localhost:8080/api/","resourcePath":"/hello","apis":[{"path":"/hello","operations":[{"method":"GET","summary":"Say Hello World","notes":"Anything Else?","type":"void","nickname":"sayHello","produces":["application/json"],"parameters":[],"responseMessages":[{"code":200,"message":"OK"},{"code":500,"message":"Something wrong in Server"}]}]}]}