public static void main(String[] args) throws Exception {
try {
DOMConfigurator.configure(Thread.currentThread().getContextClassLoader().getResource("log4j.xml"));
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(7411);
server.setConnectors(new Connector[] {connector});
DispatcherServlet servlet = new DispatcherServlet();
servlet.setContextConfigLocation("classpath:servlet-context.xml");
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addServlet(new ServletHolder("baseServlet", servlet), "/");
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[] { context, new DefaultHandler()});
server.setHandler(handlers);
XmlWebApplicationContext wctx = new XmlWebApplicationContext();
wctx.setConfigLocation("");
wctx.setServletContext(servlet.getServletContext());
wctx.refresh();
context.setAttribute(XmlWebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wctx);
server.start();
log.info("Jetty embedded server started");
log.info("Press any key to stop");
System.in.read();
log.info("Stopping Server");
server.stop();
log.info("Server stopped");
} catch (Exception ex) {
log.error("Failed to run Jetty Server", ex);
throw ex;
}
}
在JettyLauncher运行后,我们可以访问http://localhost:7411/ping来查看Jetty是否成功运行. http://localhost:7411/ping将运行以下Spring MVC Servlet:
@Controller
public class TestServlet {
private static Logger log = Logger.getLogger(TestServlet.class);
@RequestMapping(value="/ping", method = RequestMethod.GET)
public void ping(HttpServletResponse response) throws IOException {
log.info("ping page is called");
IOUtils.write("Embedded Jetty Server is Up and Running", response.getOutputStream());
}
}