maven項目引入內嵌tomcat依賴java
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <version>8.5.37</version> </dependency>
編寫以下main方法web
1 package com; 2
3 import org.apache.catalina.Context; 4 import org.apache.catalina.LifecycleException; 5 import org.apache.catalina.startup.Tomcat; 6 import org.apache.tomcat.util.descriptor.web.FilterDef; 7 import org.apache.tomcat.util.descriptor.web.FilterMap; 8 import org.springframework.web.filter.OncePerRequestFilter; 9
10 import javax.servlet.Filter; 11 import javax.servlet.FilterChain; 12 import javax.servlet.ServletException; 13 import javax.servlet.http.HttpServlet; 14 import javax.servlet.http.HttpServletRequest; 15 import javax.servlet.http.HttpServletResponse; 16 import java.io.IOException; 17 import java.nio.charset.Charset; 18
19 /**
20 * @author allen 21 * @date 2019-01-22 13:20 22 */
23 public class TomcatWebServer { 24 public static void main(String[] args) { 25 Tomcat tomcat = new Tomcat(); 26 HttpServlet httpServlet = new HttpServlet() { 27 @Override 28 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { 29 resp.getWriter().write("hello, i'm embed tomcat"); 30 } 31
32 @Override 33 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { 34 doGet(req, resp); 35 } 36 }; 37 tomcat.setHostname("localhost"); 38 tomcat.setPort(8080); 39 final Context context = tomcat.addContext("/embed-tomcat", null); 40 Tomcat.addServlet(context, "dispatch", httpServlet); 41 context.addServletMappingDecoded("/dispatch", "dispatch"); 42 Filter filter = new OncePerRequestFilter() { 43 @Override 44 protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { 45 System.out.println("filter do something"); 46 filterChain.doFilter(httpServletRequest, httpServletResponse); 47 } 48 }; 49 FilterDef filterDef = new FilterDef(); 50 filterDef.setFilter(filter); 51 filterDef.setFilterName("myFilter"); 52 filterDef.addInitParameter("userName", "Allen"); 53
54 FilterMap filterMap = new FilterMap(); 55 filterMap.addURLPatternDecoded("/*"); 56 filterMap.addServletName("*"); 57 filterMap.setFilterName("myFilter"); 58 filterMap.setCharset(Charset.forName("UTF-8")); 59
60 context.addFilterDef(filterDef); 61 context.addFilterMap(filterMap); 62 try { 63 tomcat.init(); 64 tomcat.start(); 65 tomcat.getServer().await(); 66 } catch (LifecycleException e) { 67 e.printStackTrace(); 68 } 69 } 70 }
注意其中OncePerRequestFilter是spring提供的對filter接口的實現類,沒有引入spring依賴的可自行改用其餘實現類。spring
運行main方法,一個最簡單的tomcat實例已經運行起來。瀏覽器打開http://localhost:8080/embed-tomcat/dispatch,頁面能夠看到輸出內容,控制檯也打印了過濾器執行的內容。apache
springboot默認就是使用tomcat做爲內嵌容器的,基本原理通上述代碼,只不過spring作了更深層次的封裝,結合其ioc容器,能夠實現只要往ioc容器中注入servlet、filter接口的實現類,spring的適配器可自動完成配置。瀏覽器