我正在尝试将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错误。
我在线阅读了很多例子但由于某些原因我似乎无法使处理程序正常工作。难道我做错了什么?感谢
答案 0 :(得分:1)
我遇到了完全相同的问题,这只是对Jetty API如何工作的误解。我期望使用ContextHandlers作为REST服务的最小实现,但ContextHandlers旨在处理对整个上下文基础的请求(例如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();