SpringMVC是Spring的一个组件,所以咱们在应用SpringMVC的时候也会应用到Spring

应用环境

  • JDK:1.8
  • Tomcat:9.0.3
  • spring:5.2.8
  • 编译器:IDEA2019

1、导包

须要引入Spring-web和Spring-webmvc两个包,能够到maven仓库外面去下载或者应用maven依赖

2、ApplicationContext.xml配置(Spring的外围配置文件)

  • ApplicationContext.xml文件须要放在WEB-INF下,并且须要把名字改为拦挡的serlvet-name+ -Servlet,比方我这边的拦挡名字为mvc,所以我须要把配置文件名改为mvc-Servlet.xml
  • 如果不放在WEB-INF下,须要在web.xml文件中进行门路配置(如下web.xml文件中的init-param标签配置)
  • 留神命名空间的问题
<?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 https://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">    <!-- 开启spring注解驱动-->     <context:component-scan base-package="com.cjh"/>    <!-- 开启mvc注解驱动-->     <mvc:annotation-driven></mvc:annotation-driven></beans>

3、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">     <servlet> <servlet-name>mvc</servlet-name>     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>     <init-param> <param-name>contextConfigLocation</param-name>     <!-- 阐明Spring外围配置文件的地位-->     <param-value>classpath:ApplicationContext.xml</param-value>     </init-param> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name>     <url-pattern>*.do</url-pattern>     </servlet-mapping></web-app>

4、java的实现

  • Controller类
@Controller@RequestMapping("userController.do")public class UserController {     public UserController(){         System.out.println("controller创立了");     }     @RequestMapping     public void test(){         System.out.println("controller:test办法执行了");     } }
  • index.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" %><html><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>cai jin hong</title> <style> </style></head><body> <a href="userController.do">测试</a></body></html>
  • 申请和响应流程:

    • 当点击测试超链接时,浏览器向服务器发送userController.do的资源申请
    • 服务器接管到之后,找到类下面带有@RequestMapping("userController.do")注解的对象
    • 找到了之后,查找办法下面带有@RequestMapping("xxx")注解的办法

      • 如果只有一个办法,能够不必写名字,间接写RequestMapping
      • 如果有多个办法,须要注明办法名
    • 找到了之后,执行办法,并将解决信息响应回给浏览器(该代码中没有返回值)

本篇文章只讲了一下最根本的时候,下一篇文章会具体的说的SpringMVC申请和响应的解决!!!