1:Spring MVC入门案例
1.1:导入相关依赖
<groupId>com.ysj</groupId> <artifactId>springmvc_01_quickstart</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <!-- servlet依赖--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- Spring MVC 依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.10.RELEASE</version> </dependency> </dependencies> <!--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>
1.2:创建Spring MVC配置类
//springmvc配置类,本质上还是一个spring配置类 @Configuration @ComponentScan("com.itheima.controller") public class SpringMvcConfig { }
1.3:创建并配置表现层控制的bean
//定义表现层控制器bean @Controller public class UserController { //设置映射路径为/save,即外部访问路径 @RequestMapping("/save") //设置当前操作返回结果为指定json数据(本质上是一个字符串信息) @ResponseBody public String save(){ System.out.println("user save ..."); return "{'info':'springmvc'}"; } //设置映射路径为/delete,即外部访问路径 @RequestMapping("/delete") @ResponseBody public String delete(){ System.out.println("user save ..."); return "{'info':'springmvc'}"; } }
1.4:创建web容器配置类
//web容器配置类 public class test extends AbstractDispatcherServletInitializer { //加载Spring MVC配置类,产生SpringMVC容器(本质上还是Spring容器) protected WebApplicationContext createServletApplicationContext() { //初始化WebApplicationContext对象 AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext(); //加载指定配置类 webApplicationContext.register(SpringMvcConfig.class); return webApplicationContext; } //设置由SpringMVC控制器处理的请求映射路径 protected String[] getServletMappings() { return new String[]{"/"}; } //加载Spring配置类 protected WebApplicationContext createRootApplicationContext() { return null; } }