Pie*_*ine 3 java rest jetty jersey gradle
是否可以以编程方式将 Jersey RESTful 服务附加到 Jetty 运行程序?我不清楚如何从 Web 服务类中创建 Servlet 对象。
换句话说,是否可以在没有web.xml文件的情况下创建 Jersey Web 服务并将其附加到我们自己实例化的服务器?
网络服务
@Path("/hello")
public class HelloWebapp {
@GET()
public String hello() {
return "Hi !";
}
}
Run Code Online (Sandbox Code Playgroud)
码头跑者
public class JettyEmbeddedRunner {
public void startServer() {
try {
Server server = new Server();
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/test");
new ServletContextHandler(server, "/app", true, false) {{
addServlet(new ServletHolder(HelloWorldServlet.class), "/world");
}};
server.addConnector(new ServerConnector(server) {{
setIdleTimeout(1000);
setAcceptQueueSize(10);
setPort(8080);
setHost("localhost");
}});
server.start();
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Gradle 依赖项
dependencies {
compile 'org.eclipse.jetty:jetty-server:9.0.0.RC2'
compile 'org.eclipse.jetty:jetty-servlet:9.0.0.RC2'
compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.14'
}
Run Code Online (Sandbox Code Playgroud)
正如您在 web.xml 中使用的那样
<servlet>
<servlet-name>Jersey App</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
...
</sevlet>
Run Code Online (Sandbox Code Playgroud)
您也可以ServletContainer
独立使用。
ResourceConfig config = new ResourceConfig();
config.packages("...");
ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(config));
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看完整的示例