Spring MVC 入门案例

<project>
    <dependencies>
        <!-- 1.导入坐标springmvc与servlet -->
        <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-webmnv</artifactId>
            <version>5.2.10.RELEASES</version
        </dependency>
    </dependencies>
</project>
// 2. 定义controller
// 2.1 使用@Controller定义bean
@Controller
public class UserController {

    // 2.2设置当前操作的访问路径
    @RequestMapping("/save")
    // 2.3设置当前操作的返回值类型
    @ResponseBody
    public String save(){
        System.out.println("user save ...");
        return "{'module':'springmvc'}";
    }
}
// 3.创建springmvcde配置文件,加载controller对应的bean
@Configuration
@ComponentScan("com.xxx.controller")
public class SpringMvcConfig {

}
// 4. 定义一个servlet容器启动的配置类,在里面加载spring的配置
public class ServletContainersInitConif extends AbstractDispatcherServletInitializer {
    // 加载springMVC容器配置
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringMvcConifg.class);
        return ctx;
    }

    // 设置哪些请求归属springMVC处理
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    // 加载spring容器处理
    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }
}
<!--配置tomacat插件-->
<project>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomct.maven</groupId>
                <artifactId>tomact7-maven-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <port>80</port>
                    <path>/</path>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>