内嵌tomcat最简单用法

时间:2022-03-15 15:26:32

maven项目引入内嵌tomcat依赖

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>8.5.37</version>
</dependency>

编写如下main方法

 package com;

 import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset; /**
* @author allen
* @date 2019-01-22 13:20
*/
public class TomcatWebServer {
public static void main(String[] args) {
Tomcat tomcat = new Tomcat();
HttpServlet httpServlet = new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().write("hello, i'm embed tomcat");
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doGet(req, resp);
}
};
tomcat.setHostname("localhost");
tomcat.setPort(8080);
final Context context = tomcat.addContext("/embed-tomcat", null);
Tomcat.addServlet(context, "dispatch", httpServlet);
context.addServletMappingDecoded("/dispatch", "dispatch");
Filter filter = new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
System.out.println("filter do something");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
};
FilterDef filterDef = new FilterDef();
filterDef.setFilter(filter);
filterDef.setFilterName("myFilter");
filterDef.addInitParameter("userName", "Allen"); FilterMap filterMap = new FilterMap();
filterMap.addURLPatternDecoded("/*");
filterMap.addServletName("*");
filterMap.setFilterName("myFilter");
filterMap.setCharset(Charset.forName("UTF-8")); context.addFilterDef(filterDef);
context.addFilterMap(filterMap);
try {
tomcat.init();
tomcat.start();
tomcat.getServer().await();
} catch (LifecycleException e) {
e.printStackTrace();
}
}
}

注意其中OncePerRequestFilter是spring提供的对filter接口的实现类,没有引入spring依赖的可自行改用其他实现类。

运行main方法,一个最简单的tomcat实例已经运行起来。浏览器打开http://localhost:8080/embed-tomcat/dispatch,页面可以看到输出内容,控制台也打印了过滤器执行的内容。

springboot默认就是使用tomcat作为内嵌容器的,基本原理通上述代码,只不过spring做了更深层次的封装,结合其ioc容器,可以实现只要往ioc容器中注入servlet、filter接口的实现类,spring的适配器可自动完成配置。