SpringMVC框架是什么?
SpringMVC是一种基于Java 实现 MVC模型 的 轻量级 Web框架,本质可以认为是对 servlet的封装,简化了我们servlet的开发,能够接收请求 并返回响应,跳转页面
SpringMVC主要干什么事情?
1.使用简单,开发便捷(相比于Servlet)
2.灵活性强
SpringMVC入门 实现步骤:
【第一步】创建web工程(Maven结构)
【第二步】设置tomcat服务器,加载web工程(tomcat插件)
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
【第三步】导入坐标(SpringMVC+Servlet)
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
</dependencies>
导入相关依赖和插件时可以看到上面有飘红,这时候我们把红框里的42-78行创建项目时自带的给删掉就可以了,因为这些东西我们目前暂时还用不到
【第四步】定义处理请求的功能类(UserController)
//定义表现层控制器bean
@Controller
public class UserController {
//设置映射路径为/save,外部访问路径
@RequestMapping("/save")
//设置当前操作返回结果为json数据(本质上是一个字符串信息)
@ResponseBody
public String save(){
System.out.println("user save ...");
return "{'shuiguo':'xiangjiao'}";
}
}
【第五步】编写SpringMVC配置类,加载处理请求的Bean。
//springmvc配置类,本质上还是一个spring配置类
@Configuration
@ComponentScan("com.itheima.controller")
public class SpringMvcConfig {
}
【第六步】加载SpringMVC配置,并设置SpringMVC请求拦截的路径
//web容器配置类
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
//加载springmvc配置类,产生springmvc容器(本质还是spring容器)
protected WebApplicationContext createServletApplicationContext() {
//初始化WebApplicationContext对象
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
//加载指定配置类
ctx.register(SpringMvcConfig.class);
return ctx;
}
//设置由springmvc控制器处理的请求映射路径
protected String[] getServletMappings() {
return new String[]{"/"};
}
//加载spring配置类
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}
运行
运行结果