🍁博客主页:👉 不会压弯的小飞侠
✨欢迎关注:👉点赞👍收藏⭐留言✒
✨如果觉得博主的文章还不错的话,请三连支持一下博主。
🔥欢迎大佬指正,一起 学习!一起加油!
一、入门案例
1.导入SpringMVC坐标与servlet坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.22.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
2.创建SpringMVC控制器(相当于servlet功能)
package com.study.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller //定义Bean
public class UserController {
@RequestMapping("/save")
@ResponseBody //设置当前操作的返回值类型
public String save(){
System.out.println("user save....");
return "{'module':'SpringMVC'}";
}
}
3.创建SpringMVC的配置文件
package com.study.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.study.controller")
public class SpringMvcConfig {
}
4.定义一个Servlet容器启动的配置类加载Spring的配置
package com.study.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
//加载SpringMVC容器配置
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringMvcConfig.class);
return ctx;
}
//设置哪些请求可以归属SpringMVC处理
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
//加载Spring容器配置
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}
运行结果: