java - Jetty servlet url 和端口

标签 java servlets jetty

确定运行 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/

相关文章:

java - 想要从ear文件中提取特定的jar文件并将其存储在特定目录中

java - 如何使用 Spring Ldap 模板更新密码?

java - 使用嵌套目录将文件名转换为完整目录路径的优化方法用于大文件存储

java - EJB注入(inject)时出现空指针异常

java - java 中的嵌入式 jetty 9.4 不支持 DSA 密码套件

amazon-ec2 - 亚马逊 EC2 : Jetty Unaccessible

java - org.apache.jasper.el.E​​LContextImpl 无法转换为 org.apache.jasper.runtime.ELContextImpl

java - Hibernate Envers Criteria API 自动添加 'order by' 子句

java - 在 Servlet RequestDispatcher 中发送两个属性

java - servlet错误请求的资源()不可用