|
| 1 | +package com.baeldung.tomcat; |
| 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 | + |
| 9 | +import java.io.File; |
| 10 | + |
| 11 | +/** |
| 12 | + * Created by adi on 1/10/18. |
| 13 | + */ |
| 14 | +public class ProgrammaticTomcat { |
| 15 | + |
| 16 | + private Tomcat tomcat = null; |
| 17 | + |
| 18 | + //uncomment for live test |
| 19 | + // public static void main(String[] args) throws LifecycleException, ServletException, URISyntaxException, IOException { |
| 20 | + // startTomcat(); |
| 21 | + // } |
| 22 | + |
| 23 | + public void startTomcat() throws LifecycleException { |
| 24 | + tomcat = new Tomcat(); |
| 25 | + tomcat.setPort(8080); |
| 26 | + tomcat.setHostname("localhost"); |
| 27 | + String appBase = "."; |
| 28 | + tomcat |
| 29 | + .getHost() |
| 30 | + .setAppBase(appBase); |
| 31 | + |
| 32 | + File docBase = new File(System.getProperty("java.io.tmpdir")); |
| 33 | + Context context = tomcat.addContext("", docBase.getAbsolutePath()); |
| 34 | + |
| 35 | + //add a servlet |
| 36 | + Class servletClass = MyServlet.class; |
| 37 | + Tomcat.addServlet(context, servletClass.getSimpleName(), servletClass.getName()); |
| 38 | + context.addServletMappingDecoded("/my-servlet/*", servletClass.getSimpleName()); |
| 39 | + |
| 40 | + //add a filter and filterMapping |
| 41 | + Class filterClass = MyFilter.class; |
| 42 | + FilterDef myFilterDef = new FilterDef(); |
| 43 | + myFilterDef.setFilterClass(filterClass.getName()); |
| 44 | + myFilterDef.setFilterName(filterClass.getSimpleName()); |
| 45 | + context.addFilterDef(myFilterDef); |
| 46 | + |
| 47 | + FilterMap myFilterMap = new FilterMap(); |
| 48 | + myFilterMap.setFilterName(filterClass.getSimpleName()); |
| 49 | + myFilterMap.addURLPattern("/my-servlet/*"); |
| 50 | + context.addFilterMap(myFilterMap); |
| 51 | + |
| 52 | + tomcat.start(); |
| 53 | + //uncomment for live test |
| 54 | + // tomcat |
| 55 | + // .getServer() |
| 56 | + // .await(); |
| 57 | + } |
| 58 | + |
| 59 | + public void stopTomcat() throws LifecycleException { |
| 60 | + tomcat.stop(); |
| 61 | + tomcat.destroy(); |
| 62 | + } |
| 63 | +} |
0 commit comments