最近在做一些简单的Servlet开发的时候,感觉每次调试的时候都要发布到tomcat上很麻烦,把程序共享给同事也很麻烦,需要帮他设置本地的tomcat环境. 在网上找了找其他的Servlet运行环境,发现用Jetty可以很方便的实现嵌入式Web container.这里我记录一下通过Jetty搭建简单Servlet运行环境的过程,希望对有同样需要的朋友有所帮助.
整个环境的代码可以在找到. 代码包括了IntelliJ的项目文件,如果需要eclipse项目文件,请在下载代码后运行 mvn eclipse:eclipse 来生成eclipse项目文件. (当然, 请在本地安装Maven).
- 设置Maven Dependency:
org.eclipse.jetty jetty-server ${jetty.version} org.eclipse.jetty jetty-servlet ${jetty.version} org.springframework spring-webmvc ${spring.version} log4j log4j 1.2.17 org.apache.commons commons-io 1.3.2 - 设置servlet-context.xml:
- 一个简单的Main Class:
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:
@Controllerpublic 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()); }}
通过Jetty,我们可以很容易的在本地运行和调试Servlet,而生成好的Servlet我们可以直接发布到Tomcat. 这样,我们可以简化Servlet的开发和调试.