测试环境:
tomcat-6.0.14
ubuntu gusty
sun-jdk-1.6
多个人合作的项目里只要修改tomcat-conf.properties文件后即可使用。我这里用了slf4j做LOG,不用LOG的把相关类去掉即可。还有我是把tomcat/lib下的jar都加进classpath的。
目录结构
/-|projectHome
|
|--src
| |--TomcatServer.java
| |--tomcat-conf.properties
|
|--webapp
| |--WEB-INF
| | |-web.xml
TomcatServer.java:
1 import java.io.File;
2 import java.io.IOException;
3 import java.util.Properties;
4
5 import org.apache.catalina.Context;
6 import org.apache.catalina.Engine;
7 import org.apache.catalina.Host;
8 import org.apache.catalina.LifecycleException;
9 import org.apache.catalina.startup.Embedded;
10 import org.slf4j.Logger;
11 import org.slf4j.LoggerFactory;
12
13 /**
14 * http://www.blogjava.net/jarod
15 * @author jarod
16 */
17 public class TomcatServer {
18
19 private static final Logger logger = LoggerFactory
20 .getLogger(TomcatServer.class);
21
22 public static void main(String[] args) {
23 try {
24 new TomcatServer();
25 } catch (Throwable t) {
26 logger.error("", t);
27 }
28 }
29
30 private Embedded tomcat;
31
32 // tomcat主目录
33 private String catalinaHome;
34
35 private String projectHome;
36
37 public TomcatServer() {
38 initConf();
39
40 tomcat = new Embedded();
41 tomcat.setCatalinaHome(catalinaHome);
42 Engine engine = tomcat.createEngine();
43 Host host = tomcat.createHost("localhost", projectHome);
44 host.addChild(tomcat.createContext("", ""));
45 Context context = tomcat.createContext("/webapp1", "webapp");
46 // 当以debug模式启动时,修改可立即生效
47 context.setReloadable(true);
48 host.addChild(context);
49 engine.addChild(host);
50 engine.setDefaultHost("localhost");
51 tomcat.addEngine(engine);
52 tomcat.addConnector(tomcat.createConnector("0", 8081, false));
53 registerShutdownHook();
54 try {
55 tomcat.start();
Thread.sleep(Long.MAX_VALUE);
56 } catch (Exception e) {
57 throw new RuntimeException(e);
58 }
59 }
60
61 private void initConf() {
62 Properties properties = new Properties();
63 try {
64 properties.load(TomcatServer.class
65 .getResourceAsStream("/tomcat-conf.properties"));
66 catalinaHome = properties.getProperty("catalina.home");
67
68 File f = new File(".");
69 projectHome = f.getAbsolutePath();
70 } catch (IOException e) {
71 throw new RuntimeException(e);
72 }
73 }
74
75 private void registerShutdownHook() {
76 Runtime.getRuntime().addShutdownHook(new Thread() {
77 @Override
78 public void run() {
79 try {
80 tomcat.stop();
81 } catch (LifecycleException e) {
82 throw new RuntimeException(e);
83 }
84 }
85 });
86 }
87 }
tomcat-conf.properties:
catalina.home=/home/jarod/server/tomcat/apache-tomcat-6.0.14
为什么要
setCatalinaHome?
设了该值,tomcat启动时会在该目录加载默认的一些配置,如MIME mapping等,如果要自己手动添加配置太麻烦了,而如果不要这些配置,这个embedded tomcat用处也不大