1.導入springMvc的基本jar包
1 <!--springMvc依賴的jar包--> 2 <dependency> 3 <groupId>org.springframework</groupId> 4 <artifactId>spring-webmvc</artifactId> 5 <version>5.1.3.RELEASE</version> 6 </dependency>
成功導入后在擴展包中有如下jar包:

2.配置web.xml文件
<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.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>
在resources文件夾下創建文件spring.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 http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!--啟動springMVC的注解功能,自動注冊HandlerMapping HandlerAdapter ExceptionResolver實例--> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <!--配置自動掃包--> <context:component-scan base-package="com.mmfm"></context:component-scan> <!--配置視圖解析器 如何把handler 方法返回的值解析為物理視圖--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".do"></property> </bean> </beans>
3.在WEB-INF中創建views文件夾並創建login.do文件
4.控制器,並將結果返回到自定義視圖中
@Controller public class loginController { @GetMapping("/login") public String hi(){ return "login"; } }
5.在瀏覽器中請求http://localhost/initmvc_war/login,dispatcherServlet攔截該請求並調用控制器中的login的hi方法,返回視圖login,(需要配置 <mvc:annotation-driven /> <mvc:default-servlet-handler />),否則將看到查找不到映射 /WEB-INF/login.do
