11、创建项目
2、如果在main中没有java类需要自己创建
3、把pom.xml里面东西清空
4、引入spring-webmvc包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
5、把webapp-WEB-INF中的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">
</web-app>
6、写入注册内容
<!--注册DispatcherServlet-->
<servlet>
<servlet-name>springmvc01</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--classpath编译后的路径-->
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<!--servlet映射 /表示任意路径 -->
<servlet-mapping>
<servlet-name>springmvc01</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
7、在Java中创建名为com.XX.Controller包名
8、创建springmvc.xml,也就是以下里面的内容
创建地方
写入1、包扫描、开启注解驱动、视图映射
<!-- 包扫描-->
<context:component-scan base-package="XXXX"/>//Java中controller包名
<!-- 开启注解驱动-->
<mvc:annotation-driven/>
<!-- 视图映射-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
9、在weapp下创建一个views包
1》创建一个main.jsp文件(文件随便命名)
2》在jsp文件中写入”测试成功或者其他内容“
10、在Controller中创建类进行测试
@Controller//表示该类为控制层类---等价于WebServlet
public class Hello {
@RequestMapping("/hello")//把请求路径hell映射到该方法中
public String hello(){
System.out.println("====hello===");
return "main";//经过视图解析器,/views/main.jsp
}
}
11、部署tomcat,运行
这里我把访问写为”/“,后期好访问
12、成功页面
输入@RequestMapping后的输入内容
额外:如果报以下错误
将下面的代码复制到springmvc.xml文件中替换<beans中内容
<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">