springMVC配置注解驱动的作用

版权声明:转载请注明原文链接 https://blog.csdn.net/weixin_42529699/article/details/88085405

一、springMVC的整体架构和执行流程

1、 用户发起请求到前端控制器(DispatcherServlet),前端控制器没有能力处理业务逻辑;

2、 通过HandlerMapping查找模型(Controller、Handler);

3、 返回执行链,执行链包含了2部分内容,Handler对象以及拦截器(组);

4、 通过HandlerAdapter执行模型(Handler)

5、 适配器调用Handler对象处理业务逻辑;

6、 模型处理完业务逻辑,返回ModelAndView对象,view不是真正的视图对象,而是视图名称;

7、 将ModelAndView对象返回给前端控制器;

8、 前端控制器通过视图名称经过视图解析器查找视图对象;

9、 返回视图对象;

10、前端控制器渲染视图;

11、返回给前端控制器;

12、前端控制器将视图(html、json、xml、Excel)返回给用户;

二、前端控制器的核心配置文件

 使用springMVC必须配置的三大件:

处理器映射器、处理器适配器、视图解析器

三、springMVC的配置文件

<?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:p="http://www.springframework.org/schema/p"
    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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 注册HandlerMapping -->
    <!-- <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> -->
    
    <!-- 注册简单适配器 -->
    <!-- <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> -->
    
    <!-- 推荐使用的注解的HandlerMapping -->
    <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
    
    <!-- 推荐使用的注解适配器 -->
    <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->

    <!-- mvc的注解驱动 -->
    <mvc:annotation-driven/>
    <!-- 扫描包,使@Controller生效 -->
    <context:component-scan base-package="com.xxx.springmvc.controller"/>   
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/views/"/>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

通常,我们只需要手动配置视图解析器,而处理器映射器处理器适配器只需要开启注解驱动即可,而省去了大段的xml配置

这是为什么呢?

看一下源码就明白了: 

猜你喜欢

转载自blog.csdn.net/weixin_42529699/article/details/88085405
今日推荐