0%

tomcat嵌入式

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);
// 创建一个StandardContext
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) {
// prevent it from looking ( if it finds one - it'll have dup error )
((ContextConfig) config).setDefaultWebXml(noDefaultWebXmlPath());
}

if (host == null) {
getHost().addChild(ctx);
} else {
host.addChild(ctx);
}

return ctx;
}

欢迎关注我的其它发布渠道