内嵌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();
}
}