1.使用maven创建一个web工程
2.在pom.xml文件下引入springmvc的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
3.创建controller层
注意:
@controller :表示该类为controller类
@RequestMapping :映射请求 (注解报错请往下阅读)
4.配置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: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/context
https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--1.包扫描 扫描我们自己的控制层类所在的包或者父包-->
<context:component-scan base-package="com.yanci"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
</beans>
5.替换web文件并引入前端控制器
因为博主已经替换过了就又新建了个项目演示这一块
替换为:(2.3的配置太低了,我们改为4.0的)
<?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">
6.配置映射路径
<servlet>
<servlet-name>springmvc</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>
</servlet>
<!--servlet映射路径
/: 表示所有的控制层路径 以及静态资源
/*: 表示全部 包含jsp网页
-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
7.测试
访问的为映射的路径,这样加比较好区分,每个路径都具有唯一性!