我正在尝试将Jetty 8(8.1.18.v20150929)嵌入到Java(jdk1.7.0_67)应用程序中。我有以下代码:
public static final String HTTP_PATH = "/session";
public static final int HTTP_PORT = 9995;
// Open the HTTP server for listening to requests.
logger.info("Starting HTTP server, Port: " + HTTP_PORT + ", Path: "
+ "/session");
httpServer = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(HTTP_PORT);
connector.setHost("localhost");
httpServer.addConnector(connector);
TestHttpHandler handler = new TestHttpHandler(this);
ContextHandler ch = new ContextHandler();
ch.setContextPath(HTTP_PATH);
ch.setHandler(handler);
httpServer.setHandler(ch);
try {
httpServer.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我的处理程序作为测试非常基本:
public void handle(String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
logger.debug("Handling");
}
如果我运行该应用程序,然后使用 CURL 向 http://localhost:9995/session 发送 GET 请求,则它会返回 200 状态,但没有调试输出。
如果我访问 http://localhost:9995/session2,则会收到 404 错误。
我在网上阅读了很多示例,但由于某种原因,我似乎无法让处理程序正常工作。我做错了什么吗?谢谢
我遇到了完全相同的问题,这只是对 Jetty API 工作原理的误解。我期望使用上下文处理程序作为REST服务的最小实现,但是上下文处理程序旨在处理对整个上下文库的请求(例如 http://server:80/context-base,即相当于Tomcat中的应用程序)。解决这个问题的正确方法是使用 Servlets:
Server server = new Server(9995);
ServletContextHandler root = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);
root.setContextPath("/");
ServletHolder holder = new ServletHolder(new HttpServlet() {
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
logger.debug("Handling");
}
});
server.start();
server.join();