是否可以通过java实现Jetty服务器,它将侦听不同的端口并具有两个不同的处理程序(ServletContextHandler / extends AbstractHandler)? 我有一个json请求/响应服务,可以在端口8899(扩展AbstractHandler)和在一个Jetty服务器上的端口8080(ServletContextHandler)上工作的webapp上工作。
这是ServletContextHandler,正在监听8080:
private static ServletContextHandler getServletContextHandler() throws IOException {
WebAppContext contextHandler = new WebAppContext();
contextHandler.setErrorHandler(null);
contextHandler.setContextPath(CONTEXT_PATH);
WebApplicationContext context = getContext();
contextHandler.addServlet(new ServletHolder(new DispatcherServlet(context)), CONTEXT_PATH);
contextHandler.addEventListener(new ContextLoaderListener(context));
contextHandler.setResourceBase(new ClassPathResource("webapp").getURI().toString());
contextHandler.setDescriptor("/webapp/WEB-INF/webstat.xml");
return contextHandler;
}
private static WebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("webapp/WEB-INF/");
log.info("CONTEXT name {} locations {}", context.getDisplayName(), context.getConfigLocations());
return context;
}
听取8899的处理程序:
private class Handler extends AbstractHandler {
public void handle(String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
String contentEncoding = request.getHeader(RpcClient.CONTENT_ENCODING);
String contentType = request.getHeader(RpcClient.CONTENT_TYPE);
if ((contentEncoding != null && contentEncoding.startsWith(RpcClient.APPLICATION_JSON))||
contentType.equals(RpcClient.APPLICATION_JSON)) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
}
baseRequest.setHandled(true);
}
}
最后实现Jetty服务器的方法:
public void init() {
try {
Server httpServer = new Server();
ServerConnector rpcConnector = new ServerConnector(httpServer);
rpcConnector.setHost("localhost");
rpcConnector.setPort(8899);
rpcConnector.setIdleTimeout(30000);
ServerConnector httpConnector = new ServerConnector(httpServer);
httpConnector.setHost("localhost");
httpConnector.setPort(8080);
httpConnector.setIdleTimeout(30000);
httpServer.setConnectors(new Connector[] {rpcConnector, httpConnector});
HandlerList handlerList = new HandlerList();
handlerList.setHandlers(new Handler[] {new Handler() }, new ContextHandler(getServletContextHandler()) {});//CAN'T APPLY them in HandlerList
httpServer.setHandler(handlerList);
httpServer.setStopAtShutdown(true);
httpServer.start();
log.info("WebServer start ...");
httpServer.join();
} catch (Exception ex) {
log.error("Exception in http server. Exception: {}", ex.getMessage());
}
}
我检查了ContextHandlerCollection,HandlerList,HandlerCollection&等等
目标是在一个码头服务器上组合两种不同的服务。工作的逻辑是用户转到http://localhost:8080/getStatistics
,弹出mvc将json请求发送到localhost:8899
,应用程序收集统计信息,并通过json将其响应到spring mvc,它将生成带有统计信息的jsp给用户。
有没有想过如何组合这些处理程序?