tomcat嵌入式 Tomcat7开始支持嵌入式功能,增加了一个启动类org.apache.catalina.startup.Tomcat
先来看个例子
示例 示例一:映射servlet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public static void main (String[] args) throws LifecycleException { Tomcat tomcat = new Tomcat(); Context context = tomcat.addContext("/test" ,null ); Tomcat.addServlet(context, "helloServlet" , new HttpServlet() { @Override public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException { res.getWriter().write("Hello World!!!" ); } }); context.addServletMappingDecoded("/hello" ,"helloServlet" ); tomcat.init(); tomcat.start(); tomcat.getServer().await(); }
访问127.0.0.1:8080/test/hello
即可
调用start方法启动Tomcat
1 2 3 4 5 public void start () throws LifecycleException { getServer(); getConnector(); server.start(); }
还可以调用addWebapp来添加web应用
在调用start之前先调用addWebapp来添加一个web应用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 public Context addWebapp (String contextPath, String docBase) throws ServletException { return addWebapp(getHost(), contextPath, docBase); } public Context addWebapp (Host host, String contextPath, String docBase, LifecycleListener config) { silence(host, contextPath); Context ctx = createContext(host, contextPath); ctx.setPath(contextPath); ctx.setDocBase(docBase); ctx.addLifecycleListener(getDefaultWebXmlListener()); ctx.setConfigFile(getWebappConfigFile(docBase, contextPath)); ctx.addLifecycleListener(config); if (config instanceof ContextConfig) { ((ContextConfig) config).setDefaultWebXml(noDefaultWebXmlPath()); } if (host == null ) { getHost().addChild(ctx); } else { host.addChild(ctx); } return ctx; }