Spring Mvc与Tomcat的整理
-
在spring的源码基础上,新建一个模块springmvc-source-test,勾选gradle模块,选中java和web。
-
在gradle的配置文件中,引入下面2个依赖
// https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api
compileOnly group: 'javax.servlet', name: 'javax.servlet-api', version: '4.0.1'
compile(project(":spring-webmvc"))
- 参考spring的官方文档,新建一个starter类。Web on Servlet Stack (spring.io)
/**
* @author WGR
* @create 2021/11/4 -- 9:46
*/
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) {
// Load Spring web application configuration
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
// Create and register the DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(context);
ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
- 在新建一个controller类和配置类,具体如下:
/**
* @author WGR
* @create 2021/11/4 -- 9:51
*/
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello(){
return "Hello, SpringMVC!";
}
}
/**
* @author WGR
* @create 2021/11/4 -- 9:50
*/
@ComponentScan("com.dalianpai.springmvc")
@Configuration
public class AppConfig {
}
- 安装tomcat,并在idea中进行配置
- 由于spring-web的模块中是基于SPI机制实现的,在它的resources的包的下面,找到接口类的实现类,为SpringServletContainerInitializer,下面具体的如下图:
最终调用FrameworkServlet#initServletBean方法,里面在继续调用initWebApplicationContext();进行初始化容器。
原文地址:https://www.cnblogs.com/dalianpai/p/15508017.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。