Spring MVC框架主要由DispatcherServlet 处理器映射 控制器 视图解析器 视图组成 具体工作原理如下图
Spring MVC所有的请求都经过DispatcherServlet来统一分发,DispatcherServlet将请求分发给Controller之前 需要借助于Spring MVC提供的HandlerMapping定位到具体的Controller
HandlerMapping接口负责完成客户请求到Controller的映射
- <?xml version="1.0" encoding="UTF-8"?>
-
- -<web-app version="4.0" id="WebApp_ID" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-
- <!--配置springmvcDispatcherServlet-->
-
-
-
- -<servlet>
-
- <servlet-name>springmvc</servlet-name>
-
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
-
- <load-on-startup>1</load-on-startup>
-
- </servlet>
-
-
- -<servlet-mapping>
-
- <servlet-name>springmvc</servlet-name>
-
- <url-pattern>/</url-pattern>
-
- </servlet-mapping>
-
- </web-app>
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- 没注册的用户,请<a href="index/register">注册</a>!<br>
- 已注册的用户,去<a href="index/login">登录</a>!
- </body>
- </html>
- package controller;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- /**“@Controller”表示IndexController的实例是一个控制器
- * @Controller相当于@Controller("indexController")
- * 或@Controller(value = "indexController")
- */
- @Controller
- @RequestMapping("/index")
- public class IndexController {
- @RequestMapping("/login")
- public String login() {
- /**login代表逻辑视图名称,需要根据Spring MVC配置
- * 文件中internalResourceViewResolver的前缀和后缀找到对应的物理视图
- */
- return "login";
- }
- @RequestMapping("/register")
- public String register() {
- return "register";
- }
- }
- "1.0" encoding="UTF-8"?>
-
- -<beans 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans">
-
-
-
- <context:component-scan base-package="controller"/>
-
- <mvc:annotation-driven/>
-
-
-
-
-
- <mvc:resources mapping="/css/**" location="/css/"/>
-
-
-
-
- -<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
-
-
-
- <property value="/WEB-INF/jsp/" name="prefix"/>
-
-
-
- <property value=".jsp" name="suffix"/>
-
- bean>
-
- beans>