Spring MVC 3.1 <mvc:annotation-driven> quick configuration

 

 

<mvc:annotation-driven>

Some new built-in tags of this tag have been added in spring mvc 3.1, and personal capabilities are limited. The following is a brief description of this tag:

The following are optional configurations:

 

 

Html code   Favorite code
  1. <mvc:annotation-driven ignoreDefaultModelOnRedirect="true" conversion-service="" validator="" message-codes-resolver="">  
  2.         <mvc:argument-resolvers>  
  3.             <bean class="com.lay.user.util.CustomerArgumentResolver"/>  
  4.         </mvc:argument-resolvers>  
  5.         <mvc:message-converters>  
  6.             <bean class=""/>  
  7.         </mvc:message-converters>  
  8.         <mvc:return-value-handlers>  
  9.             <bean class=""/>  
  10.         </mvc:return-value-handlers>  
  11. </mvc:annotation-driven>  

So what does mvc:annotation-driven do?

Refer to the official documentation:

16.14.1 Enabling MVC Java Config or the MVC XML Namespace

 

 1. Let's talk about the mvc:annotation-driven attribute first

 

  • ignoreDefaultModelOnRedirect : The parameter when requesting redirection (redirection is to ignore the model parameter)
  • conversion-service : Type conversion during data binding. If it is not set, the FormattingConversionService will be registered by default and support joda time. Due to the limited space, joda time will not be introduced. I will talk about it when I have time.
  • validator : parameter validation, optional. If not set and jsr303.jar is added, jsr303 will be used. The implementation framework of jsr303 is hibernate-validator.jar, which may be introduced in detail later.
  • message-codes-resolver : Data binding and verification information resolution, optional, do not set the default registration DefaultMessageCodesResolver

The basic default is enough, and more advanced usage can be specified by yourself.

2.mvc:annotation-driven built-in tag

 

  •  <mvc:argument-resolvers> : parameter resolver, which can be implemented by implementing the HandlerMethodArgumentResolver interface. This implementation will not override the original spring mvc built-in parsing for parameter parsing. For custom built-in support parameter parsing, you can consider registering RequestMappingHandlerAdapter. The following is refer to:
Java code   Favorite code
  1. public class CustomerArgumentResolver implements HandlerMethodArgumentResolver {  
  2.   
  3.     public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,   
  4.             NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {  
  5.         return null;  
  6.     }  
  7.   
  8.     public boolean supportsParameter(MethodParameter parameter) {  
  9.         System.out.println(parameter.getParameterName() + " : " + parameter.getParameterName()   
  10.                 + " \nParameterType: " + parameter.getParameterType() + " \nMethod: " + parameter.getMethod().getName());  
  11.         return false;  
  12.     }  
  13.   
  14. }  

 Code description:  The supportsParameter method mainly determines whether the parameter is supported by the parser, support: true, not support: false 

               If it returns true, the resolveArgument method is called.

 

 So where will our custom parameter parsing be called? Look down:

 

Let's look at the implementation class of HandlerMethodArgumentResolver:

Unable to insert pictures. . . . . It hurts

Look at the code:

 

Java code   Favorite code
  1. /** 
  2.  * Resolves method parameters by delegating to a list of registered {@link HandlerMethodArgumentResolver}s. 
  3.  * Previously resolved method parameters are cached for faster lookups. 
  4.  * 
  5.  * @author Rossen Stoyanchev 
  6.  * @since 3.1 
  7.  */  
  8. public class HandlerMethodArgumentResolverComposite implements HandlerMethodArgumentResolver {  
  9.        /** 
  10.      * Find a registered {@link HandlerMethodArgumentResolver} that supports the given method parameter. 
  11.      */  
  12.     private HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) {  
  13.         HandlerMethodArgumentResolver result = this.argumentResolverCache.get(parameter);  
  14.         if (result == null) {  
  15.             for (HandlerMethodArgumentResolver methodArgumentResolver : argumentResolvers) {  
  16.                 if (logger.isTraceEnabled()) {  
  17.                     logger.trace("Testing if argument resolver [" + methodArgumentResolver + "] supports [" +  
  18.                             parameter.getGenericParameterType() + "]");  
  19.                 }  
  20.                 if (methodArgumentResolver.supportsParameter(parameter)) {  
  21.                     result = methodArgumentResolver;  
  22.                     this.argumentResolverCache.put(parameter, result);  
  23.                     break;  
  24.                 }  
  25.             }  
  26.         }  
  27.         return result;  
  28.     }  
  29. }  

 

 解析参数的时候会自动找到HandlerMethodArgumentResolverComposite 这个 HandlerMethodArgumentResolver实现类,然后调用他的supportsParameter方法,supportsParameter方法会去判断是否支持该参数的解析,而我们自定义的参数解析器也被注入到for 循环中的argumentResolvers参数中了,不会上传图片,没法截图给大家看了,这里简单说下:

        argumentResolvers是一个参数解析器集合,我们自定义的解析器会出现在这里,spring mvc默认把RequestParamMethodArgumentResolver 和ServletModelAttributeMethodProcessor重复注册到最后,

 spring mvc会一次找到supportsParameter方法返回true的解析器,并调用该方法的resolveArgument方法进行解析。

 

具体大家自己动手实现一下吧,不过多啰嗦了~!

 

  • mvc:return-value-handlers:对返回值的处理。自定义实现类需要实现HandlerMethodReturnValueHandler,这个和上面提到的mvc:argument-resolvers自定义实现类的使用上几乎没差别。同样的,如果想改变内置返回值处理的话请直接注入RequestMappingHandlerAdapter,不累赘了,具体可以查看HandlerMethodReturnValueHandlerComposite源码。
  • mvc:message-converters:主要是对 @RequestBody 参数和 @ResponseBody返回值的处理,可选的,在这里注册的HttpMessageConverter默认情况下优先级是高于内置的转换器的,那么怎么自定义转换器呢?

 通过实现HttpMessageConverter<T>接口便可以了,当然,你也可以继承AbstractHttpMessageConverter<T>,这样做会更轻松,具体做法参考源码

 

Java代码   Favorite code
  1. public interface HttpMessageConverter<T> {  
  2.   
  3.       // Indicate whether the given class and media type can be read by this converter.  
  4.       boolean canRead(Class<?> clazz, MediaType mediaType);  
  5.   
  6.       // Indicate whether the given class and media type can be written by this converter.  
  7.       boolean canWrite(Class<?> clazz, MediaType mediaType);  
  8.   
  9.       // Return the list of MediaType objects supported by this converter.  
  10.       List<MediaType> getSupportedMediaTypes();  
  11.   
  12.       // Read an object of the given type from the given input message, and returns it.  
  13.       T read(Class<T> clazz, HttpInputMessage inputMessage) throws IOException,  
  14.                                                                    HttpMessageNotReadableException;  
  15.   
  16.       // Write an given object to the given output message.  
  17.       void write(T t, HttpOutputMessage outputMessage) throws IOException,  
  18.                                                               HttpMessageNotWritableException;  
  19.   
  20.     }  

 

 

At the beginning of the article, I mentioned what mvc:annotation-driven does. In fact, many converters are registered by default using mvc:annotation-driven:

 

 

 

  • StringHttpMessageConverter
  • FormHttpMessageConverter
  • ByteArrayHttpMessageConverter
  • MarshallingHttpMessageConverter
  • MappingJacksonHttpMessageConverter
  • SourceHttpMessageConverter
  • BufferedImageHttpMessageConverter

From this, I can understand the reason why I only need to add a jar package to complete the output of json when using mvc:annotation-driven in my previous article about outputting json format . Why can't xml be solved by MarshallingHttpMessageConverter?

 

Finally, mvc:annotation-driven can be used for quick configuration in development. The default injected converter is almost enough without injecting its own parser. As for other

  • RequestMappingHandlerMapping

  • RequestMappingHandlerAdapter

    Configurable properties are discussed later.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326248711&siteId=291194637