美文网首页Java
内嵌Tomcat和SpringMVC的简单整合测试

内嵌Tomcat和SpringMVC的简单整合测试

作者: 惜时流光沿途留殇 | 来源:发表于2020-12-28 11:33 被阅读0次

    内嵌Tomcat和SpringMVC的简单整合测试

    添加对外暴露的接口类

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class TestController {
        @RequestMapping("test")
        public String test(){
            System.out.println("111111");
            return "index";
        }
    }
    
    

    添加配置类信息

    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    
    @Configuration
    @ComponentScan("com.github.alenfive.rocketapi.app")
    @EnableWebMvc
    public class WebMvcConfig {
    }
    
    

    添加配置类信息

    import com.github.alenfive.rocketapi.app.WebMvcConfig;
    import org.apache.catalina.Context;
    import org.apache.catalina.LifecycleException;
    import org.apache.catalina.Wrapper;
    import org.apache.catalina.connector.Connector;
    import org.apache.catalina.startup.Tomcat;
    
    import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
    import org.springframework.web.servlet.DispatcherServlet;
    
    import java.io.IOException;
    
    //添加主类进行SpringWeb环境的初始化和Tomcat的启动
    public class ExampleMvcApplication{
    
      public static void main(String[] args) throws LifecycleException, IOException {
          Tomcat tomcat = new Tomcat();
          tomcat.setPort(80);
          Context context = tomcat.addContext("/","d:/embedTomcat/");
          Connector conn = tomcat.getConnector(); // Tomcat 9.0 必须调用 Tomcat#getConnector() 方法之后才会监听端口
          System.out.println("连接器设置完成: " + conn);
          //添加dispathServlet
          AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
          ac.register(WebMvcConfig.class);
          DispatcherServlet dispatcherServlet = new DispatcherServlet(ac);
          Wrapper wrapper = tomcat.addServlet("/", "mvc", dispatcherServlet);
          context.addServletMappingDecoded("/","mvc");
          wrapper.setLoadOnStartup(1);
          wrapper.addMapping("*");
          tomcat.start();
          tomcat.getServer().await();
      }
    
    
    }
    

    相关文章

      网友评论

        本文标题:内嵌Tomcat和SpringMVC的简单整合测试

        本文链接:https://www.haomeiwen.com/subject/tnmznktx.html