spring mvc的mvc:annotation-driven以及日期的处理

<mvc:annotation-driven />是什么意思?参考手册http://docs.spring.io/spring/docs/3.2.4.RELEASE/spring-framework-reference/pdf/spring-framework-reference.pdf会讲得比较清楚
17.15 Configuring Spring MVC讲到<mvc:annotation-driven />就是注册了一个RequestMappingHandlerMapping,一个RequestMappingHandlerAdapter和一个ExceptionHandlerExceptionResolver(其中包括)支持使用注解标注在Controller方法的处理请求,例如@RequestMapping ,@ExceptionHandler等等
它还执行以下操作:
1. Spring 3 style type conversion through a ConversionService instance in addition to the JavaBeans PropertyEditors used for Data Binding.
2. Support for  formatting Number fields using the  @NumberFormat annotation through the ConversionService.
3. Support for  formatting Date, Calendar, Long, and Joda Time fields using the @DateTimeFormat annotation.
4. Support for  validating @Controller inputs with  @Valid, if a JSR-303 Provider is present on the classpath.
5. HttpMessageConverter support for  @RequestBody method parameters and  @ResponseBody method return values from @RequestMapping or @ExceptionHandler methods.
This is the complete list of HttpMessageConverters set up by mvc:annotation-driven:
• ByteArrayHttpMessageConverter converts byte arrays.
• StringHttpMessageConverter converts strings.
• ResourceHttpMessageConverter converts to/from org.springframework.core.io.Resource for all media types.
• SourceHttpMessageConverter converts to/from a javax.xml.transform.Source.
• FormHttpMessageConverter converts form data to/from a  MultiValueMap<String,String>.
• Jaxb2RootElementHttpMessageConverter converts Java objects to/from XML — added if JAXB2 is present on the classpath.
• MappingJackson2HttpMessageConverter (or MappingJacksonHttpMessageConverter) converts to/from JSON — added if Jackson 2 (or Jackson) is present on the classpath.
• AtomFeedHttpMessageConverter converts Atom feeds — added if Rome is present on the classpath.
• RssChannelHttpMessageConverter converts RSS feeds — added if Rome is present on the classpath.


其实相信在大多数实际应用环境中使用mvc:annotation-driven是少数,因为一般都满足不了需求,但想快速搭配环境还是比较适合的.当使用java config,记得有文章介绍不推荐配置RequestMappingHandlerMapping和RequestMappingHandlerAdapter


如果不使用mvc:annotation-driven,日期又如何处理.

spring mvc默认是支持yyyy-MM-dd格式的字符串转换为java的java.util.Date.包括spring mvc框架本身和spring mvc支持的jackson.
对于其它格式的日期的字符串与Java的Date对象相互转化,一样可分为两种情况:
A:一种普通请求,前台的日期字符串与后台的Java Date对象转化,此情况,应使用spring mvc本身的内置日期处理.
B:另一种将参数写进请求体里面,使用application/json这样的mediaType发请求,对于此情况,应使用Jackson的序列化和反序列化来处理.

一.第1种情况(不要忘了加joda-time包哦):
1.先使用@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")在Controller的方法参数或VO的属性使用.
2.如果不使用mvc:annotation-driven,那么使用数据绑定来处理@DateTimeFormat这样的注解.配置例子如下:

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="webBindingInitializer">
            <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
                <property name="conversionService" ref="conversionService" />
            </bean>
        </property>
        <property name="messageConverters">
            <list>
                <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>application/json; charset=UTF-8</value>
                            <value>text/html; charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>
    <bean id="conversionService" class="org.springframework.format.support.DefaultFormattingConversionService"/>
二.第2种情况:
1.继承定义序列化和反序列化类.例子:
public class DateJsonSerializer extends JsonSerializer<Date> {
    public static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        jsonGenerator.writeString(format.format(date));
    }
}
public class DateJsonDeserializer extends JsonDeserializer<Date> {
    public static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        try {
            return format.parse(jsonParser.getText());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}
2.在VO使用@JsonSerialize(using = DateJsonSerializer.class)和@JsonDeserialize(using = DateJsonDeserializer.class)注解(属性或方法都可以,序列化标注在get方法,反序列化标注在set方法).

@JsonSerialize(using = DateJsonSerializer.class)

@JsonDeserialize(using = DateJsonDeserializer.class)

private Date createTime;

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
使用<mvc:annotation-driven>标签时,可能会出现以下错误: 1. 找不到org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping类 这个错误通常是由于Spring版本不兼容导致的。如果您使用的是Spring 3.1或更高版本,则应该使用<mvc:annotation-driven>标签。如果您使用的是Spring 3.或更低版本,则应该使用<context:component-scan>标签。 2. 找不到org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter类 这个错误通常是由于Spring版本不兼容导致的。如果您使用的是Spring 3.1或更高版本,则应该使用<mvc:annotation-driven>标签。如果您使用的是Spring 3.或更低版本,则应该使用<context:component-scan>标签。 3. 找不到org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter类 这个错误通常是由于Spring版本不兼容导致的。如果您使用的是Spring 5.或更高版本,则应该使用@EnableWebMvc注释。如果您使用的是Spring 4.或更低版本,则应该使用WebMvcConfigurerAdapter类。 4. 找不到org.springframework.web.servlet.DispatcherServlet类 这个错误通常是由于您没有正确配置DispatcherServlet导致的。请确保您已经正确配置了DispatcherServlet,并且在web.xml文件中正确地映射了它。 5. 找不到org.springframework.web.servlet.view.InternalResourceViewResolver类 这个错误通常是由于您没有正确配置InternalResourceViewResolver导致的。请确保您已经正确配置了InternalResourceViewResolver,并且在Spring配置文件中正确地定义了它。 总之,当使用<mvc:annotation-driven>标签时,如果出现错误,请检查您的Spring版本和配置是否正确。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值