57、springmvc-整合

57.1 创建Spring MVC Annotation项目

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hw</groupId>
    <artifactId>Spring MVC Annotation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <!--打包的时候排除-->
            <scope>provided</scope>
        </dependency>

    </dependencies>

</project>

57.2 自定义 WebApplicationContext

/**
 * @Description web 容器启动的时候 调用方法来初始化容器以及前端控制器
 */
public class WebApplicationContext extends AbstractAnnotationConfigDispatcherServletInitializer {
    /**
     * 获取根容器的配置类
     *
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{RootConfig.class};
    }

    /**
     * 获取web容器的配置文件
     *
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{AppConfig.class};
    }

    /**
     * 获取servlet 映射信息
     * / : 拦截所有资源  但不包括  *.jsp
     * /* : 拦截所有资源  包括  *.jsp
     * <p>
     * jsp 页面是tomcat的jsp引擎解析的
     *
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

57.3 AppConfig and RootConfig

//  不扫描 controller  父容器
@ComponentScan(value = "com.hw", 
excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class})})
public class RootConfig {
}
// spring mvc 只扫描 controller   子容器
@ComponentScan(value = "com.hw",
        useDefaultFilters = false,
        includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class})})
public class AppConfig {
}