【问题标题】:Migration from Jetty 6 to Jetty 8从 Jetty 6 迁移到 Jetty 8
【发布时间】:2012-02-14 14:47:53
【问题描述】:

我在简单的应用程序中使用 jetty6 作为嵌入式 servlet 容器。我决定将其更新为 Jetty 8。 在 jetty 6 中,启动服务器非常简单:

Server server = new Server(8080);
Context context = new Context(server, "/", Context.SESSIONS);
context.addServlet(MyServlet.class, "/communication-service");
server.start();

但它在 Jetty8 中不起作用。 不幸的是,我找不到这个版本的任何简单示例。无法实例化 Context 错误

an enclosing instance that contains
    org.eclipse.jetty.server.handler.ContextHandler.Context is required

因为现在它是一个内部类,也没有这样的构造函数。

大多数示例都是针对 6 号和 7 号码头的。 您能否提供一个简单的示例,如何在 jetty 8 启动 servlet?

【问题讨论】:

  • 您的问题缺乏细节。什么不起作用?哪条线路导致问题?尝试运行时是否有堆栈跟踪?
  • 我在一些 Jetty 6 代码中遇到了同样的问题。我有两个将服务器作为参数的Contexts。在 Jetty 8 中,模式似乎是相反的,因为您在服务器中有一个 setHandler 方法(对于单个处理程序)。但似乎没有任何文档涉及如何迁移具有多个附加到同一服务器的上下文的代码。这是您打算使用上下文处理程序集合的情况吗?
  • 啊,搞定了。下面蒂姆的回答就是我所需要的,每个 servlet 都有多个 handler.addServlet 调用。

标签: java servlets jetty


【解决方案1】:

这是与您的代码等效的 Jetty 8。它仍然和以前一样简单,但是 API 略有变化。

如果这对您不起作用,那么您可能遇到了类路径问题 - Jetty 8 被分成许多独立的 jar 文件,您将需要其中的一些。至少你需要:

  • 码头继续
  • 码头-http
  • 码头-io
  • 码头安全
  • 码头服务器
  • jetty-servlet
  • 码头实用工具
  • servlet-api

如果你有这些罐子,那么这段代码应该可以正常工作:

package test;

import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;

public class Jetty8Server {
    public static class MyServlet extends HttpServlet {
        protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
            response.setContentType("text/plain");
            response.getWriter().write(getClass().getName() + " - OK");
        }
    }
    public static void main(String[] args) throws Exception {
        Server server = new Server(8080);
        ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS);
        handler.setContextPath("/"); // technically not required, as "/" is the default
        handler.addServlet(MyServlet.class, "/communication-service");
        server.setHandler(handler);
        server.start();
    }
}

【讨论】:

    【解决方案2】:

    Jetty 现在是 Eclipse 的一部分。文档 here 适用于 Jetty 7,但声称它应该适用于 Jetty 8。页面末尾有一个使用 servlet 的示例。

    【讨论】:

    • 这个例子也不行。没有像 ServletContextHandler 和 ServletHolder 这样的类
    • 那么你做错了什么,因为 Jetty 8 Javadoc 列出了这些类。
    • 我添加了 maven 依赖 org.eclipse.jetty jetty-server 8.1。那里有什么问题? dl.dropbox.com/u/12053587/jetty1.png
    • 您的屏幕截图显示您缺少 jetty-servlet JAR,这是我下载的 Jetty 8 中这些类所在的位置。我下载的 JAR 比您拥有的要多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    相关资源
    最近更新 更多