使用ServletContext嵌入Jetty 9

时间:2014-03-25 02:03:33

标签: java servlets jetty-9

我尝试使用此处的示例尝试从Jetty 7升级到Jetty 9:

http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html#d0e18177

Server server = new Server(8080);
ServletContextHandler context=new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
HttpServlet servlet=new TestServlet();
context.addServlet(new ServletHolder(servlet), "/*");
server.setHandler(context);
server.start();
server.join();

然而,它在运行时死亡:

java.lang.NullPointerException
at org.eclipse.jetty.util.component.ContainerLifeCycle.addBean(ContainerLifeCycle.java:304)
at org.eclipse.jetty.util.component.ContainerLifeCycle.addBean(ContainerLifeCycle.java:213)
at org.eclipse.jetty.server.Server.<init>(Server.java:128)
at org.eclipse.jetty.server.Server.<init>(Server.java:103)

示例中的servlet是一个简单的hello world样本。

1 个答案:

答案 0 :(得分:3)

以下是使用提供的Jetty“DefaultServlet”类使用Jetty9 Embedded / Servlets的示例。

public static void main(String[] args) throws Exception {
  Server server = new Server(8080);
  ServletContextHandler context=new ServletContextHandler(ServletContextHandler.SESSIONS);
  context.setContextPath("/");
  DefaultServlet defaultServlet = new DefaultServlet();
  ServletHolder holderPwd = new ServletHolder("default", defaultServlet);
context.addServlet(holderPwd, "/*");
  server.setHandler(context);
  server.start();
  server.join();
}

输出:

  

2014-04-08 10:04:18.173:INFO :: main:记录初始化@ 132ms   2014-04-08 10:04:18.243:INFO:oejs.Server:main:jetty-9.1.3.v20140225   2014-04-08 10:04:18.282:INFO:oejsh.ContextHandler:main:已开始o.e.j.s.ServletContextHandler@52e21a17 {/,null,AVAILABLE}   2014-04-08 10:04:18.298:INFO:oejs.ServerConnector:main:已启动ServerConnector @ 7388665b {HTTP / 1.1} {0.0.0.0:8080}   2014-04-08 10:04:18.298:INFO:oejs.Server:main:已启动@ 259ms