SpringMvc 數據綁定400錯誤

LIFE日誌php

starscream日誌html

今天請求一個SpringMvc 的時候,客戶端老是報出:web

The request sent by the client was syntactically incorrectspring

網上都是說的是bean的名字和表單的名字不同,可是我檢查了N多遍以後,仍是有報這個異常,就想到了SpringMvc 自動裝配的問題。mvc

而後看日誌說是""轉爲int類型的時候不能夠爲空;ide

應該就是數據綁定的問題了,通過一番研究,springMvc的數據綁定有幾種方式:spa

1,controller 獨享日誌

2,全局共享orm


controller獨享方式: xml

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(
            dateFormat, false));
}


全局共享:        

全局共享方式有幾種實現方法:

繼承 WebBindingInitializer 接口來實現全局註冊

使用@InitBinder只能對特定的controller類生效,爲註冊一個全局的customer Editor,能夠實現接口WebBindingInitializer 。

 

public class CustomerBinding implements WebBindingInitializer {
    @Override
    public void initBinder(WebDataBinder binder, WebRequest request) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                dateFormat, false));

    }

xml配置文件:

 

<bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">
            <bean
                class="net.zhepu.web.customerBinding.CustomerBinding" />
        </property>
    </bean>

 


使用conversion-service來註冊自定義的converter  

DataBinder實現了PropertyEditorRegistry, TypeConverter這兩個interface,而在spring mvc實際處理時,返回值都是return binder.convertIfNecessary(見HandlerMethodInvoker中的具體處理邏輯)。所以能夠使用customer conversionService來實現自定義的類型轉換。

配置文件:

<!-- 自定義類型轉換 -->
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.cms.common.util.DateConverter" />
                <bean class="com.cms.common.util.IntegerConverter" />
                <bean class="com.cms.common.util.LongConverter" />
            </list>
        </property>
    </bean>

實現類:

public class LongConverter implements Converter<String,Long>{

    @Override
    public Long convert(String text) {
        if (StringUtil.isEmpty(text))return 0l;
        try {
            return Long.parseLong(text);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return 0l;
    }

}

xml配置converter:

<!-- 解決亂碼 -->
    <mvc:annotation-driven conversion-service="conversionService">
        <mvc:message-converters register-defaults="true">
            <bean class="com.cms.common.db.UTF8StringHttpMessageConverter" />
        </mvc:message-converters>
    </mvc:annotation-driven>
相關文章
相關標籤/搜索