前言

这里为了后面的springboot源码分析做铺垫,让你更加充分理解springboot如何内嵌tomcat的一篇文章

编码

1、依赖

compile("org.springframework:spring-webmvc:5.2.11.RELEASE")
compile("org.springframework:spring-web:5.2.11.RELEASE")
compile("javax.servlet:javax.servlet-api:3.1.0")
compile("org.apache.tomcat.embed:tomcat-embed-core:8.5.28")
compile("org.apache.tomcat:tomcat-jasper:8.5.28")
compile("org.apache.maven.plugins:maven-compiler-plugin:3.5.1")

2、容器加载

public class WebInitializar implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) {
        // 创建容器
        AnnotationConfigWebApplicationContext app = new AnnotationConfigWebApplicationContext();
        // 配置自定义配置文件
        app.register(SpringMvcConfig.class);
        // 注册
        DispatcherServlet dispatcherServlet = new DispatcherServlet(app);
        ServletRegistration.Dynamic dynamic = servletContext.addServlet("dispatcherServlet", dispatcherServlet);
        dynamic.addMapping("/");
        // 优先级
        dynamic.setLoadOnStartup(1);
    }
}

3、扫描注解

@EnableWebMvc
@Configuration
@ComponentScan("com.qw.springmvc.example.tomcat.controller")
public class SpringMvcConfig {
}

4、rest接口

@RestController
public class IndexController {

    @RequestMapping("/test")
    public String index(){
        return "springmvc-tomcat";
    }
}

5、启动方法

public class SpringMvcTomcatApplication {

    public static int TOMCAT_PORT = 9090;
    public static String TOMCAT_HOSTNAME = "127.0.0.1";
    public static String WEBAPP_PATH = "src/main";
    public static String WEBINF_CLASSES = "/WEB-INF/classes";
    public static String CLASS_PATH = "build/classes";
    public static String INTERNAL_PATH = "/";

    public static void main(String[] args) throws LifecycleException, ServletException {
        Tomcat tomcat = new Tomcat();
        tomcat.setHostname(TOMCAT_HOSTNAME);
//         tomcat 信息保存在项目下
        tomcat.setBaseDir(".");
        tomcat.setPort(TOMCAT_PORT);
//        StandardContext ctx = (StandardContext) tomcat.addWebapp("/tomcat",new File("src/main").getAbsolutePath());
        StandardContext ctx = (StandardContext) tomcat.addWebapp("/tomcat", System.getProperty("user.dir") + File.separator + WEBAPP_PATH);
        ctx.setReloadable(false);
//        ctx.addLifecycleListener(new AprLifecycleListener());
        WebResourceRoot resourceRoot = new StandardRoot(ctx);
        resourceRoot.addPreResources(new DirResourceSet(resourceRoot, WEBINF_CLASSES, System.getProperty("user.dir") + File.separator + CLASS_PATH, INTERNAL_PATH));
//        File file = new File(CLASS_PATH);
//        resourceRoot.addPreResources(new DirResourceSet(resourceRoot, "/build/classes", file.getAbsolutePath(),"/"));
        // 注册servlet
//        tomcat.addServlet("/tomcat", "demoServlet", new DemoServlet());
//        ctx.addServletMappingDecoded("/demo.do", "demoServlet");
        tomcat.start();
        tomcat.getServer().await();
    }

验证

image.png

上一篇 下一篇