一、SpringMVC的介绍
SpringMVC是一种基于Java实现MVC模型的轻量级Web框架,可以理解为这个框架包含了servlet的功能并代替了它。
二、SpirngMVC的依赖坐标
<!--springmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
最重要的SpringMVCConfig.java配置类:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@ComponentScan({
"cn.itheima.controller","cn.itheima.config"})
//其实controller和servlet是相似的处理前端页面和后端的链接的是web层框架
//扫描controller下的类中的注解,尽量将springmvc的注解和spring的注解分开扫描,不会占过多不必要的内存
//毕竟spring的bean和springmvc的bean的格式不同也用不上
@EnableWebMvc
public class SpringMVCConfig {
}
三、对SpringMVC进行配置
使用SpringMVC其实是在tomcat接收到浏览器的请求后将请求交给DispatcherServlet,将DispatcherServlet加入到Spring中让DispatcherServlet来对后台的controller,Bean等进行管理。
DispatchaerServlet.java(注释里面有详细解释)
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
import javax.servlet.Filter;
//这个文件在tomcat开启会被自动扫描
public class DispatcherServlet extends AbstractDispatcherServletInitializer {
// 为啥web的ioc不一样,因为这里东西给springMVC的dispatcherServlet调用,所以跟以前容器的结构不一样
/*
* 保存格式: 键:访问路径 值:{当前controller对象,当前对象中的方法}
* */
// 让Controller的类(bean)加载进web的ioc容器中,这个容器中的内容是为了让dispatcherServlet执行的
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
annotationConfigWebApplicationContext.register(SpringMVCConfig.class);
return annotationConfigWebApplicationContext;
}
//设置springmvc的管理范围
@Override
protected String[] getServletMappings() {