1.导包:
SprngMvc是Spring的web模块,所有模块的运行都依赖核心模块(IOC模块)
导入核心模块所需要的包:
导入web模块需要的jar包:
2.写web.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--SpringMvc中有一个前端控制器拦截所有的请求,并智能派发-->
<!--这个前端控制器是一个Servlet-->
<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:springmvc.xml</param-value>
</init-param>
<!--服务器启动的时候创建对象-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>MyFirstController</servlet-name>
<servlet-class>com.hh.controller.MyFirstController</servlet-class>
</servlet>
<!--
/:拦截所有请求,但是不会拦截*.jsp,能保证jsp访问正常
/*:拦截所有请求,按包括前端页面
-->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.编写springmvc.xml配置文件:开启注解支持,扫描所有组件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--扫描所有组件-->
<context:component-scan base-package="com.hh"/>
</beans>
4.编写前端页面:index.jsp
<a href="hello">helloworld!!!</a>
5.编写跳转页面:success.jsp
<h3>成功页面</h3>
6.编写控制层类
//将这个组件交给容器管理
@Controller
public class MyFirstController {
//从当前项目开始,处理当前项目下的hello请求
@RequestMapping("/hello")
public String test(){
System.out.println("请求收到了...正在处理中");
return "/WEB-INF/pages/success.jsp";
}
}
7.配置Tomcat服务器:
8.测试结果:
入门案例的执行流程
- 当启动Tomcat服务器的时候,因为配置了load-on-startup标签,所以会创建DispatcherServlet对象,
就会加载springmvc.xml配置文件 - 开启了注解扫描,那么MyFirstController对象就会被创建
- 从index.jsp发送请求,请求会先到达DispatcherServlet核心控制器,根据配置@RequestMapping注解找到执行的具体方法
- 执行到return时,跳转到跳转页面
- Tomcat服务器渲染页面,做出响应