Spring MVC 配置
一、工作流程
DispatcherServlet接收Client请求
根据HandlerMapping映射到Handler
生成Handler和HandlerInterceptor,组装成HandlerExecutionChain返还给DispatcherServlet
DispatcherServlet通过HandlerAdapter调用Handler方法并返回一个ModelAndView
DispatcherServlet将ModelAndView传给ViewResolver解析成View
DispatcherServlet渲染View并返回给Client
二、如何使用
新建maven工程,骨架选webapp,导入依赖:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.7.RELEASE</version> </dependency>
在web.xml中配置DispatcherServlet:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <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:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
注意springmvc.xml是自己建立在resources目录下的文件。
接下来配置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-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.wts"></context:component-scan> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="suffix" value=".jsp"></property> <property name="prefix" value="/"></property> </bean> </beans>
创建Controller:
package com.wts.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloHandler { @RequestMapping("/index") public String index() { return "index"; } }
配置Tomcat并启动(需要提前安装)