最近在看李号双老师的《深入拆解Tomcat&Jetty》专栏,思路超清楚,看到源码就怕怕的我也可以看的很欢脱,想看源码一起揭秘呢……
and 老师建议的第一步就是搞个嵌入式的tomcat玩起来,然后断点调试,还贴心地甩了个demo。我天……晕了晕了,找了个适合我这种小渣渣看的示例,超清楚!转发!!!
李号双老师推荐的示例:https://github.com/heroku/devcenter-embedded-tomcat
我找的这位大佬的文章:Java Web 学习笔记之十六:嵌入式web服务器Tomcat的基本使用
对着李号双老师讲的Tomcat框架来看,这份代码非常好上手,也很好理解。推荐直接跳转看哦,排版也是美的美的,俺只是个实名搬运工。
嵌入式Tomcat服务器则无需部署外置tomcat,开发者只需引入嵌入式tomcat依赖,编写少量启动代码即可运行Web应用,是搭建微服务应用的首选方式之一。
建一个简单的maven工程就可以啦,不必是Java web哦。pom.xml文件的内容如下:
4.0.0
com.ellie
tomcat
1.0-SNAPSHOT
9.0.19
org.apache.tomcat.embed
tomcat-embed-core
${tomcat.version}
org.apache.tomcat.embed
tomcat-embed-jasper
${tomcat.version}
org.apache.tomcat
tomcat-jasper
${tomcat.version}
org.apache.tomcat
tomcat-jasper-el
${tomcat.version}
org.apache.tomcat
tomcat-jsp-api
${tomcat.version}
TomcatSample
org.apache.maven.plugins
maven-compiler-plugin
3.1
1.8
build部分是可选的,主要是因为用的开发工具是IntelliJ IDEA,默认Java5,所以每次都会粘个方便的build过来。
简单的意思就是tomcat可以启起来,然后啥也没得(后面有介绍添加servlet的方法的啦~)
public class MyTomcat {
public static void main(String[] args) throws Exception {
// 创建临时目录作为tomcat的基础目录
Path tempBaseDir = Files.createTempDirectory("tomcat-temp-base-dir");
// 创建临时目录作为应用文档资源的目录
Path tempDocDir = Files.createTempDirectory("tomcat-temp-doc-dir");
Tomcat tomcat = new Tomcat();
Connector connector = new Connector();
// 设置绑定端口
connector.setPort(8080);
tomcat.getService().addConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
tomcat.setBaseDir(tempBaseDir.toFile().getAbsolutePath());
// 创建应用上下文
String contextPath = "/ellie";
StandardContext context = (StandardContext) tomcat.addWebapp(
contextPath, tempDocDir.toFile().getAbsolutePath());
context.setParentClassLoader(MyTomcat.class.getClassLoader());
context.setUseRelativeRedirects(false);
// TODO:添加servlet
//tomcat 启动jar扫描设置为跳过所有,避免与框架结合出现 jar file not found exception
System.setProperty("tomcat.util.scan.StandardJarScanFilter.jarsToSkip", "\\,*");
tomcat.start();
tomcat.getServer().await();
}
}
附上李号双老师讲课给的Tomcat框架图:
添加Servelt有三种方式:
三种使用方式的代码如下:
// addServlet方法添加
{
tomcat.addServlet(contextPath, "test1Name", TestServlet.class.getName());
//注意不要忘记设置Servlet路径映射
context.addServletMappingDecoded("/test1Path/*", "test1Name");
}
// Wrapper对象进行配置
{
Wrapper wrapper = context.createWrapper();
wrapper.setName("test2Name");
wrapper.setServletClass(TestServlet2.class.getName());
context.addChild(wrapper);
context.addServletMappingDecoded("/test2Path/*", "test2Name");
}
这两种方法对应的Servlet写法如下:
public class TestServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().println("Hello, world! -1-");
}
}
第三种方式添加servlet是直接在Servlet上使用注解,示例如下:
@WebServlet(name = "test3", urlPatterns = {"/test3/*"})
public class TestServlet3 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().println("Hello, world! -3-");
}
}
使用这种方式需要保证配置的资源集 中包含有该类型的(class资源集合或lib资源集合),也就是要告诉Tomcat怎么找到它。
代码如下:
private static void configureResources(StandardContext context) {
String WORK_HOME = System.getProperty("user.dir");
File classesDir = new File(WORK_HOME, "target/classes");
File jarDir = new File(WORK_HOME, "lib");
WebResourceRoot resources = new StandardRoot(context);
if (classesDir.exists()) {
resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes", classesDir.getAbsolutePath(), "/"));
System.out.println("Resources added: [classes]");
} else if (jarDir.exists()) {
resources.addJarResources(new DirResourceSet(resources, "/WEB-INF/lib", jarDir.getAbsolutePath(), "/"));
System.out.println("Resources added: [jar]");
} else {
resources.addPreResources(new EmptyResourceSet(resources));
System.out.println("Resources added: [empty]");
}
context.setResources(resources);
}
代码说明:
最后成型的代码如下:
public class MyTomcat {
public static void main(String[] args) throws Exception {
// 创建临时目录作为tomcat的基础目录
Path tempBaseDir = Files.createTempDirectory("tomcat-temp-base-dir");
// 创建临时目录作为应用文档资源的目录
Path tempDocDir = Files.createTempDirectory("tomcat-temp-doc-dir");
Tomcat tomcat = new Tomcat();
Connector connector = new Connector();
// 设置绑定端口
connector.setPort(8080);
tomcat.getService().addConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
tomcat.setBaseDir(tempBaseDir.toFile().getAbsolutePath());
// 创建应用上下文
String contextPath = "/ellie";
StandardContext context = (StandardContext) tomcat.addWebapp(
contextPath, tempDocDir.toFile().getAbsolutePath());
context.setParentClassLoader(MyTomcat.class.getClassLoader());
context.setUseRelativeRedirects(false);
// 添加servlet
configureServlets(contextPath, tomcat, context);
configureResources(context);
//tomcat 启动jar扫描设置为跳过所有,避免与框架结合出现 jar file not found exception
System.setProperty("tomcat.util.scan.StandardJarScanFilter.jarsToSkip", "\\,*");
tomcat.start();
tomcat.getServer().await();
}
private static void configureResources(StandardContext context) {
String WORK_HOME = System.getProperty("user.dir");
File classesDir = new File(WORK_HOME, "target/classes");
File jarDir = new File(WORK_HOME, "lib");
WebResourceRoot resources = new StandardRoot(context);
if (classesDir.exists()) {
resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes", classesDir.getAbsolutePath(), "/"));
System.out.println("Resources added: [classes]");
} else if (jarDir.exists()) {
resources.addJarResources(new DirResourceSet(resources, "/WEB-INF/lib", jarDir.getAbsolutePath(), "/"));
System.out.println("Resources added: [jar]");
} else {
resources.addPreResources(new EmptyResourceSet(resources));
System.out.println("Resources added: [empty]");
}
context.setResources(resources);
}
private static void configureServlets(String contextPath, Tomcat tomcat, StandardContext context) {
{
tomcat.addServlet(contextPath, "test1Name", TestServlet.class.getName());
//注意不要忘记设置Servlet路径映射
context.addServletMappingDecoded("/test1Path/*", "test1Name");
}
{
Wrapper wrapper = context.createWrapper();
wrapper.setName("test2Name");
wrapper.setServletClass(TestServlet2.class.getName());
context.addChild(wrapper);
context.addServletMappingDecoded("/test2Path/*", "test2Name");
}
}
}
通过浏览器访问:
其中的ellie是俺设置的contextPath啦。然后访问的时候就发现会生成临时目录:
这三个部分暂时没有用到,不过大佬封装一下,看着很干净,列出来啦:
private static void configureContextParameters(StandardContext context) {
context.addParameter("param1", "1");
context.addParameter("param2", "2");
}
private static void configureFilters(StandardContext context) {
//Filter定义
FilterDef filterDef = new FilterDef();
filterDef.setFilterName("test-filter");
filterDef.setFilterClass(TestFilter.class.getName());
filterDef.addInitParameter("name", "test-filter");
context.addFilterDef(filterDef);
//Filter路径映射
FilterMap filterMap = new FilterMap();
filterMap.setFilterName("test-filter");
filterMap.addURLPattern("/*");
context.addFilterMap(filterMap);
}
private static void configureListeners(StandardContext context) {
context.addApplicationEventListener(new TestListener());
}
用到的Filter:
public class TestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Enumeration enumeration = filterConfig.getInitParameterNames();
if (enumeration.hasMoreElements()) {
String name = enumeration.nextElement();
System.out.println(String.format("Filter init: init-param name:[%s], value:[%s]", name, filterConfig.getInitParameter(name)));
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println(String.format("Filter doFilter: remote host: [%s]", request.getRemoteHost()));
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
用到的Listener:
public class TestListener implements LifecycleListener {
@Override
public void lifecycleEvent(LifecycleEvent event) {
if (event != null && event.getLifecycle() != null) {
System.out.println(event.getLifecycle().getStateName() + "ellie");
}
if (!(event.getLifecycle() instanceof Server)) {
return;
}
if (!Lifecycle.AFTER_START_EVENT.equals(event.getType())) {
return;
}
Server server = (Server) event.getLifecycle();
}
}