Spring-mvc学习,mvc:annotation-driven标签的作用

昝浩阔
2023-12-01

前言

本文是学习SpringMVC框架中,记录作者的学习心得,如有纰漏,欢迎指点.


1.一些注解的前提配置,如果没有开启这个标签.有些注解就没有办法解析

解决了@Controller注解的使用前提配置context:annotation-config/是对包进行扫描,实现注释驱动Bean定义,同时将bean自动注入容器中使用。即解决了@Controller标识的类的bean的注入和使用。 mvc:annotation-driven会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean,这是Spring MVC为@Controller分发请求所必需的.如当你注解了@ControllerAdvice(处理全局异常的注解),当你没添加这个mvc:annotation-driven这个标签,可能没法正确处理掉异常.

2.mvc:annotation-driven标签提供enable-matrix-variables="true"属性.

该属性默认是关闭的(false),手动开启后,我们可以处理URL地址带有矩阵变量的请求.
<mvc:annotation-driven enable-matrix-variables=“true”/>

3.支持解析Joda-Time类型的数据.

Spring-mvc配置文件中,mvc:annotation-driven标签,需要设置conversion-service属性,并配置该对象.代码如下:
<mvc:annotation-driven conversion-service=“conversionService”/>

<bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="org.example.MyConverter"/>
        </set>
    </property>
    <property name="formatters">
        <set>
            <bean class="org.example.MyFormatter"/>
            <bean class="org.example.MyAnnotationFormatterFactory"/>
        </set>
    </property>
    <property name="formatterRegistrars">
        <set>
            <bean class="org.example.MyFormatterRegistrar"/>
        </set>
    </property>
</bean>

但是我也不太懂Joda-Time这个类型的数据

4.支持Validator对象的注册

Spring-mvc配置文件中,<mvc:annotation-driven />标签设置
validator=globalValidator属性代码如下:
<mvc:annotation-driven validator=“globalValidator”/>

Validator对象,这个我也不太懂

5.支持的json数据的接收和反馈.

说白了,就是允许请求中带有json数据,反馈中允许发送json数据.我们在处理异步请求时,大概率是要用到json数据,所以带有json数据的交互时,我们必须在Spring-mvc主配置文件中,添加<mvc:annotation-driven>标签.

最后,我在学习<mvc:annotation-driven>标签时,查看了Spring-mvc原文文档的同时,还查阅了一些博客.

下面的链接是我觉得比较好的博客
https://blog.csdn.net/qq_35029061/article/details/82945761

 类似资料: