gpt4 book ai didi

java - 独立的 Java EE 应用服务器

转载 作者:行者123 更新时间:2023-12-02 04:51:09 25 4
gpt4 key购买 nike

我正在开发独立应用程序。

应用程序像java -jar myapp.jar一样启动,并且没有部署在任何地方。我需要使用嵌入式应用程序服务器。

到目前为止我只找到Jetty ,但它并不支持所有 Java EE 功能。还有其他选择吗?

最佳答案

我肯定会选择 tomee 。基本上它是带有 j2ee 类固醇的 tomcat :p

============

这些是代码,我在本地笔记本电脑上测试了它,它应该可以工作。注意,你需要从这个link下载tomee-embedded.jar嵌入式 jar 的源代码可以在 here 中找到。如果您想了解代码中到底发生了什么。

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

import javax.ejb.embeddable.EJBContainer;

import org.apache.openejb.loader.IO;
import org.apache.tomee.embedded.EmbeddedTomEEContainer;


public class Main {

public static void main(String[] args) {
EJBContainer container = null;
try {
System.out.println("Start");
final File war = createWar();
final Properties p = new Properties();
p.setProperty(EJBContainer.APP_NAME, "test");
p.setProperty(EJBContainer.PROVIDER, EmbeddedTomEEContainer.class.getName());
p.put(EJBContainer.MODULES, war.getAbsolutePath());
p.setProperty(EmbeddedTomEEContainer.TOMEE_EJBCONTAINER_HTTP_PORT, "-1");

System.out.println(war.getAbsolutePath());

container = EJBContainer.createEJBContainer(p);
System.out.println(container);
System.out.println(container.getContext());
final URL url = new URL("http://127.0.0.1:" + System.getProperty(EmbeddedTomEEContainer.TOMEE_EJBCONTAINER_HTTP_PORT) + "/test/index.html");
System.out.println(getOk(url, 2));

} catch (Throwable e) {
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
} finally {

if (container != null) {
container.close();
}
}
}
private static String getOk(final URL url, final int tries) throws Exception {
try {
return IO.readProperties(url).getProperty("ok");
} catch (final IOException e) {
if (tries > 0) {
Thread.sleep(1000);
return getOk(url, tries - 1);
} else {
throw e;
}
}
}

private static File createWar() throws IOException {
final File file = new File(System.getProperty("java.io.tmpdir") + "/tomee-" + Math.random());
if (!file.mkdirs() && !file.exists()) {
throw new RuntimeException("can't create " + file.getAbsolutePath());
}

write("ok=true", new File(file, "index.html"));
write("<beans />", new File(file, "WEB-INF/classes/META-INF/beans.xml"));
return file;
}

private static void write(final String content, final File file) throws IOException {
if (!file.getParentFile().mkdirs() && !file.getParentFile().exists()) {
throw new RuntimeException("can't create " + file.getParent());
}

final FileWriter index = new FileWriter(file);
index.write(content);
index.close();
}
}

关于java - 独立的 Java EE 应用服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29225553/

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