Tomcat 7 Embeded 用法

參考實例代碼:java

 

 1 package com.scdsun.learntomcat;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 import javax.servlet.ServletException;
 7 
 8 import org.apache.catalina.LifecycleException;
 9 import org.apache.catalina.core.AprLifecycleListener;
10 import org.apache.catalina.core.StandardServer;
11 import org.apache.catalina.startup.Tomcat;
12 
13 public class MyServer {
14     private static String PROJECT_PATH = System.getProperty("user.dir");
15     private static String WEB_APP_PATH = PROJECT_PATH + File.separator
16             + "webapps";
17     private static String CATALINA_HOME = PROJECT_PATH;
18 
19     public static void main(String[] args) throws LifecycleException,
20             IOException, ServletException {
21         Tomcat tomcat = new Tomcat();
22         tomcat.setPort(8080);
23         // 將會在相應目錄下生產jsp原文件及對應的class
24         // 如這裏使用應用程序的根目錄:D:\Workspace_Eclipse\LearnTomcat\work\Tomcat\localhost\Hello\org\apache\jsp
25         // 其中D:\Workspace_Eclipse\LearnTomcat\爲CATALINA_HOME
26         // 後續的work\Tomcat\localhost\Hello\org\apache\jsp爲tomcat生成的文件
27         tomcat.setBaseDir(CATALINA_HOME);
28         // Web應用所存放的目錄,如:D:\Workspace_Eclipse\LearnTomcat\webapps
29         // 在這個目錄下存放須要發佈的Web應用
30         tomcat.getHost().setAppBase(WEB_APP_PATH);
31 
32         try {
33             StandardServer server = (StandardServer) tomcat.getServer();
34             AprLifecycleListener listener = new AprLifecycleListener();
35             server.addLifecycleListener(listener);
36             
37             // 添加一個根路徑應用,如http://localhost:8080/
38             tomcat.addWebapp("/", WEB_APP_PATH + File.separator + "ROOT");
39             // 添加一個/Hello應用,如: http://localhost:8080/Hello/
40             tomcat.addWebapp("/Hello", WEB_APP_PATH + File.separator + "Hello");
41         } catch (ServletException e) {
42             e.printStackTrace();
43             throw e;
44         }
45         try {
46             tomcat.start();
47             tomcat.getServer().await();
48         } catch (LifecycleException e) {
49             e.printStackTrace();
50             throw e;
51         }
52 
53     }
54 }

服務啓動後:web

一、因爲添加了ROOT應用(tomcat.addWebapp("/", WEB_APP_PATH + File.separator + "ROOT")),能夠在本地文件夾D:\Workspace_Eclipse\LearnTomcat\webapps\ROOT中放置index.htm文件,直接訪問地址http://localhost:8080/apache

二、因爲添加了Hello/應用(tomcat.addWebapp("/Hello", WEB_APP_PATH + File.separator + "Hello")),能夠在本地文件夾D:\Workspace_Eclipse\LearnTomcat\webapps\Hello\中保存hello.jsp文件,訪問http://localhost:8080/Hello/hello.jsp進行測試;Tomcat爲hello.jsp自動生成的java和class文件,位於本地D:\Workspace_Eclipse\LearnTomcat\work\Tomcat\localhost\Hello\org\apache\jsp目錄中tomcat

相關文章
相關標籤/搜索