maven
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.70</version>
</dependency>
<!--spring-mvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.3.24</version>
</dependency>
启动代码
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
@ComponentScan
public class TomcatTest {
public static void main(String[] args) throws Exception {
//spring容器
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
//读取扫描
context.register(TomcatTest.class);
//初始化容器
context.refresh();
Tomcat tomcat = new Tomcat();
//端口
tomcat.getConnector().setPort(8082);
Context standardContext = tomcat.addContext("/请求前缀", null);
//将 DispatcherServlet 交与 tomcat
Tomcat.addServlet(standardContext, "dispatcherServlet", new DispatcherServlet(context));
standardContext.addServletMappingDecoded("/*", "dispatcherServlet");
tomcat.start();
}
}