嵌入式Tomcat实战
Java代码
1. package com.iman.opm.web.common; 2.
3. import org.apache.catalina.Context; 4. import org.apache.catalina.Engine; 5. import org.apache.catalina.Host;
6. import org.apache.catalina.connector.Connector; 7. import org.apache.catalina.startup.Embedded; 8. import java.net.InetAddress; 9. 10./**
11. * 嵌入式TOMCAT 12. */
13.public class EmbeddedTomcat { 14.
15. private String webrootPath = \ // WEB应用程序路径
16. private String contextPath = \上下文名称 17. private int tomcatPort = 80;//TOMCAT端口
18. private boolean reloadable = true; // 是否允许热交换class 19.
20. private Embedded tomcat; // 嵌入式TOMCAT 21.
22. public EmbeddedTomcat() {
23. if (System.getProperty(\
24. webrootPath = System.getProperty(\25. }
26. if (System.getProperty(\
27. contextPath = System.getProperty(\28. }
29. if (System.getProperty(\
30. reloadable = Boolean.valueOf(System.getProperty(\loadable\31. }
32. if (System.getProperty(\{
33. tomcatPort = Integer.parseInt(System.getProperty(\omcat.control.port\34. }
35. } 36.
37. /**
38. * 启动TOMCAT 39. */
40. public void startup() throws Exception {
41. System.out.println(\ting, please waiting .......\42. tomcat = new Embedded();
43. Engine engine = tomcat.createEngine(); 44. tomcat.setCatalinaHome(webrootPath); 45.
46. Host host = tomcat.createHost(\;
47. Context context = tomcat.createContext(contextPath, webrootPath);
48. if (reloadable)
49. context.setReloadable(true); 50. host.addChild(context); 51. engine.addChild(host);
52. engine.setDefaultHost(host.getName()); 53.
54. engine.setName(\55. tomcat.addEngine(engine);
56. Connector connector = tomcat.createConnector(InetAddress.getByName(\57. connector.setURIEncoding(\58. tomcat.addConnector(connector); 59. tomcat.start(); 60. } 61.
62. /**
63. * 终止TOMCAT 64. */
65. public void shutdown() throws Exception { 66. tomcat.stop(); 67. } 68.
69. public static void main(String[] args) { 70. try {
71. new EmbeddedTomcat().startup();
72. System.out.println(\ started .......\
73. } catch (Exception e) {
74. System.out.println(\failed to start .......\
75. e.printStackTrace(); 76. } 77. } 78.}
引入Tomcat相关jar包:
在WebRoot目录下面建立conf目录: conf目录放置tomcat的三个配置文件: 1、context.xml
2、tomcat-users.xml 3、web.xml
context.xml内容: Xml代码 1.
4. lt;Context privileged='true'> 5.
6.
7.
9. 11. type=\ 12. driverClassName=\ 13. url=\14. username=\15. password=\16. maxActive=\17. maxIdle=\ 18. maxWait=\19. 20. tomcat-users.xml内容: Xml代码 1. 6. 7. 8. 9.