gpt4 book ai didi

java - Jetty servlet url 和端口

转载 作者:行者123 更新时间:2023-11-29 09:55:51 24 4
gpt4 key购买 nike

确定运行 jetty servlet 的 url 和端口的方法调用是什么?这样我就可以将它打印在屏幕上,并在客户端中使用它进行连接:

url = new URL("trying to figure this out");

我在本地运行客户端和服务器,在 eclipse 中,这是一个学校项目。

相关代码:

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class ServerMain {

public static void main(String[] args){
Server server = new Server();
ServletContextHandler context =
new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("Servlet");

context.setResourceBase("etc/docroot");

server.setHandler(context);
context.addServlet(new ServletHolder(new MyServer()), "/game");
DefaultServlet staticFileServlet = new DefaultServlet();
context.addServlet(new ServletHolder(staticFileServlet), "/*");
System.out.println("context: " + context.getContextPath());
//System.out.println("One valid Port = "
+ context.getServer().getConnectors()[0].getPort());
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}

最佳答案

因为你是在做这个嵌入式的,你有几个选择。

服务器服务器=新服务器(8080);

这将在端口 8080 上启动服务器,如果这是你想要的,这很好,但在单元测试中,你通常希望这是一个随机端口,以避免 CI 或并行测试等问题相互绊倒。

服务器服务器=新服务器(0);

这将在随机端口上启动连接器,但如何获取该端口?

server.getConnectors()[0].getLocalPort();

端口实际上来自连接器,通常您只在此处设置一个连接器,因此这会为您提供该端口。

现在 localhost 可以很好地用于测试,但是如果您想要连接器所在的主机的名称,您可以使用这个:

server.getConnectors()[0].getHost();

把这些东西串联起来,你就会明白我们是如何在 Jetty 本身中进行大部分单元测试的,启动服务器本身,连接我们想要的任何处理程序或 Web 应用程序,然后断言行为、请求、响应等。

我们这里有许多嵌入式示例,您可以查看在代码中连接 jetty 的不同方法,jetty.xml 格式只是 java 上的一层薄薄的 xml,因此您可以轻松映射 jetty 的启动通过使用 java 帽子读取 xml 文件来完成代码。这里有一个嵌入式示例,用于基于该 xml 格式引导 jetty ,如果您想将配置保留在那里。

http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/example-jetty-embedded/src/main/java/org/eclipse/jetty/embedded

有关嵌入 jetty 的好页面,请看这里:http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html

关于java - Jetty servlet url 和端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12014122/

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