第一阶段,Maven导入依赖
- 要点1:因为要建立的是一个web工程,所以要在pom里追加一个war
- 要点2:引入spring-webmvc依赖(新版本5.3.18,等有机会再试)
<packaging>war</packaging>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
# 可以发现,这一个依赖就等于拥有6个依赖:
aop、beans、context、core、expression、web
第二阶段、配置前端控制器(web.xml配置)
第一步骤:新建一个web.xml工程
新建过程中,下面红字的路径,其中“src\main\webapp”是需要个人手动补充的
第二步骤:完善web.xml的内容
- 至于“classpath:mvc.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">
<servlet>
<servlet-name>mvc-fy</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc.xml</param-value><!-- 先写着,之后去做这个文件 -->
</init-param>
<load-on-startup>1</load-on-startup><!--懒汉/饿汉式选择-->
</servlet>
<servlet-mapping>
<servlet-name>mvc-fy</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 补充,用语跳转到html用。如果写的项目是JSP,不需要写这个 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
# 前端控制作用(别名:核心控制器)
1,前端接收所有请求
2,启动SpringMVC工厂 mvc.xml
3,springMVC流程调度
第三阶段,后端控制器(mvc.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描注解 -->
<context:component-scan base-package="com.fy.web"/>
<!-- 注解驱动 -->
<mvc:annotation-driven/>
</beans>
第四阶段,测试用Java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/hello") // 对应地址栏:localhost:8080/hello
public class Demo1 {
@RequestMapping("test1") // 对应地址栏:localhost:8080/hello/test1
public String test1() {
System.out.println("你好mvc1");
return "hello.html"; // 如果想要跳转到jsp页面上,去掉.html即可
}
@RequestMapping("test2")
public String test2() {
System.out.println("你好mvc2");
return "hello.html"; // 如果想要跳转到jsp页面上,去掉.html即可
}
}