SpringMVC入门
入门SpringMVC组成
核心配置文件(spring-mvc.xml):用于配置SpringMVC
核心控制器(DispathcerServlet):用于接收所有请求,使用SpringMVC接管后续工作
Controller:相当于web阶段的Servlet,用于处理相应的请求,使用相应注解可以配置处理地址
ModelAndView:模型与视图,模型可以传递一些数据和对象,视图是对应的页面
一:导入SpringMVC相关坐标
<!--Spring坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--SpringMVC坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--Servlet坐标-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--Jsp坐标-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
二:在web.xml中配置SpringMVC的核心控制器
SpringMVC核心控制器本质是一个Servlet,将所有请求交由SpringMVC框架处理。
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
三:创建Controller和相应的业务方法
创建前我们先了解几个注解。
-
@RequestMapping: 请求映射地址,相当于Servlet中的映射地址。
不同的是,该注解可以在方法上使用,每个方法就相当于一个Servlet。
-
@ResponseBody: 告知框架不进行视图跳转,直接进行数据响应
创建Controller和业务方法
@RequestMapping("/user") public class UserController { @RequestMapping("/quick2") // 此时访问该方法的地址为http://localhost:8080/工程名/user/quick2 public ModelAndView save2() { // 使用ModelAndView 返回视图 ModelAndView modelAndView = new ModelAndView(); // 向模型中添加数据 modelAndView.addObject("username","Veneno"); // 设置视图名称 modelAndView.setViewName("/pages/success.jsp"); // 跳转视图 return modelAndView; } @RequestMapping("/quick") // 此时访问该方法的地址为http://localhost:8080/工程名/user/quick public String save() { System.out.println("~~~"); 跳转视图 return "/pages/success.jsp"; } }
四:创建spring-mvc.xml配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置注解扫描-->
<context:component-scan base-package="com.itheima"/>
</beans>