gpt4 book ai didi

java - JAX-RS 网络服务的主要应用程序

转载 作者:搜寻专家 更新时间:2023-11-01 02:09:04 24 4
gpt4 key购买 nike

我目前正在实现我的第一个基于 JAX-RS 的 REST 服务,在我对 JAX-RS 的研究过程中,我发现了两个版本如何实现应用程序的主要“入口点”。一种选择是实现一个在其主要方法中启动服务器的类:

public class Spozz {
public static void main(String[] args) throws Exception {
//String webappDirLocation = "src/main/webapp/";
int port = Integer.parseInt(System.getProperty("port", "8087"));
Server server = new Server(port);

ProtectionDomain domain = Spozz.class
.getProtectionDomain();
URL location = domain.getCodeSource().getLocation();

WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setDescriptor(location.toExternalForm() + "/WEB-INF/web.xml");
webapp.setResourceBase(location.toExternalForm());
webapp.setServer(server);
webapp.setWar(location.toExternalForm());

webapp.setParentLoaderPriority(true);

// (Optional) Set the directory the war will extract to.
// If not set, java.io.tmpdir will be used, which can cause problems
// if the temp directory gets cleaned periodically.
// Your build scripts should remove this directory between deployments
webapp.setTempDirectory(new File(location.toExternalForm()));

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

另一个扩展 javax.ws.rs.core.Application 类。

@ApplicationPath("/services")
public class Spozz extends Application {
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();

public Spozz() {
singletons.add(new UserResource());
}

@Override
public Set<Class<?>> getClasses() {
return empty;
}

@Override
public Set<Object> getSingletons() {
return singletons;
}
}

然而,我在许多不同的示例中都看到了这两个版本,但从未解释过为什么选择这个版本以及有什么好处。我个人会坚持第二个,但我真的没有理由这样做。所以我的问题是:

  1. 这些选项有什么区别?
  2. 在使用 JAX-RS 2.0 时,哪个更好?
  3. 如果我想将 servlet 添加到服务中,这很重要吗?

最佳答案

What are the differences of this options?

选项 #1 实际上只是作为一个快速启动。您希望在生产环境中调整 Web 容器的许多属性,例如线程池/线程数/连接器等。我不确定您的代码与哪个嵌入式容器相关,但 Web 容器配置最好留给配置文件而不是生产中的代码。

Which one is preferable when using JAX-RS 2.0?

如果您正在制作原型(prototype),请使用#1。用于生产用途 #2。对于 Jersey 应用程序的入口点,扩展 Application 类是可行的方法。所以这不是真正的选择问题。

Is it important if I would like to add servlets to the service?

我不确定那是什么意思。您希望稍后添加 servlet 吗?无论您使用的是嵌入式容器还是独立容器,都没有关系。 Servlet 就是 servlet。它们将在容器中处理请求。

关于java - JAX-RS 网络服务的主要应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22503042/

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