我正在尝试配置嵌入式Jetty(7.6)以同时处理WebSocketHandler,ServletContextHandler和ResourceHandler类。
我尝试过使用HandlerCollection和HandlerList类,但是我无法让所有3个部分都工作。
Server server = new Server(8081);
// static files handler
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true);
resourceHandler.setResourceBase("./src/main/webapp/");
// servlet handler
ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
servletContextHandler.setContextPath("/");
servletContextHandler.addServlet(new ServletHolder(new myServlet()), "/myServlet");
// websocket handler
myWebSocketHandler myWebSocketHandler = new myWebSocketHandler();
// putting it together
HandlerCollection handlerList = new HandlerCollection();
handlerList.setHandlers(new Handler[]{resourceHandler,myWebSocketHandler,servletContextHandler});
server.setHandler(handlerList);
在这种状态下,静态文件和servlet处理得很好,但是当我发送websocket请求时,我得到:
2012-02-22 10:16:44.703:WARN:oejs.Response:Committed before 503 null
2012-02-22 10:16:44.705:WARN:oejs.AbstractHttpConnection:/
java.lang.IllegalStateException: Committed
at org.eclipse.jetty.server.Response.resetBuffer(Response.java:1080)
...
如果我检查我的websockets处理程序中的基本请求“处理”属性的状态,它已经设置为true。所以这意味着我的请求正在处理并提交到myWebSocketHandler之前提交?
感谢任何评论,谢谢。
答案 0 :(得分:6)
您是否尝试过简单地切换处理程序的顺序?
handlerList.setHandlers(new Handler[]{myWebSocketHandler,servletContextHandler,resourceHandler});
Jetty按照添加它们的顺序运行处理程序,资源处理程序处理每个请求(可能通过提供404
错误)。
答案 1 :(得分:3)
我遇到了同样的问题,但只使用了websocketHandler和resourceHandler。我解决了它将resourceHandler设置为websocketHandler:
public static void main(String[] args) {
try {
Server server = new Server(8081);
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setResourceBase("./chat");
WebSocketHandler chatWebSocketHandler = new ChatWebSocketHandler();
chatWebSocketHandler.setHandler(resourceHandler);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{chatWebSocketHandler});
server.setHandler(handlers);
server.start();
// Jetty server is stopped when the Thread is interrupted.
server.join();
} catch (Throwable e) {
e.printStackTrace();
}
}