gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:03:36 26 4
gpt4 key购买 nike

我正在尝试将 Swagger 集成到运行嵌入式 grizzly 服务器的 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 添加到灰熊服务器吗?

PS我正在使用这个依赖
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-servlet</artifactId>
<version>2.9</version>
</dependency>

最佳答案

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

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","apis":[{"path":"/hello","description":"Say Hello!"}]}



调用 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"}]}]}]}

关于servlets - 以编程方式将 servlet 添加到嵌入式灰熊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24489672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com