Spring MVC parameter Type conversions

Source: Internet
Author: User

The implementation is illustrated by the example of a string to date:

Global configuration First: implementing the Converter Interface
  • Implementation class:
    public class Stringtodateconveter implements Converter {

        private String formatPatten;    public StringToDateConveter(String formatPatten){        this.formatPatten=formatPatten;    }    @Override    public Date convert(String s) {        return DateUtil.string2Date(s,formatPatten);    }}
  • Mvc.xml configuration

      <mvc:annotation-driven conversion-service= "Conversionservice" ></MVC: Annotation-driven><bean id= "Conversionservice" class= " Org.springframework.format.support.FormattingConversionServiceFactoryBean "> <property name=" Converters "                > <set> <bean class= "Com.lannong.api.www.converter.StringToDateConveter" > <constructor-arg name= "Formatpatten" value= "Yyyy-mm-dd"/> </bean> </set> </prope Rty></bean>  
  • Configure to Handleradapter

       <!--使用 ConfigurableWebBindingInitializer 注册conversionService-->   <bean id="webBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">        <property name="conversionService" ref="conversionService"/>   </bean>   <!-- 注册ConfigurableWebBindingInitializer 到RequestMappingHandlerAdapter-->   <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">        <property name="webBindingInitializer" ref="webBindingInitializer"/>   </bean>
The second kind: Implement the Formatter interface, similar to the first implementation method
    • Implementation class

      public class MyDateFormater implements Formatter<Date> {    @Override    public Date parse(String s, Locale locale) throws ParseException {        return DateTimeUtil.string2Date(s,"yyyy-MM-dd");    }    @Override    public String print(Date date, Locale locale) {        return null;    }}
    • Mvc.xml Configuration

      <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven><bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">    <property name="formatters">        <set>            <bean class="com.lannong.api.www.converter.MyDateFormater"/>        </set>    </property></bean>
The third type: Implement Webbindinginitializer interface
    • Implementation class

      public class MyWebBindingInitializer implements WebBindingInitializer {    @Override    public void initBinder(WebDataBinder binder, WebRequest request) {        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {            @Override            public void setAsText(String text) {                setValue(DateTimeUtil.string2Date(text, "yyyy-MM-dd"));            }        });    }}
    • Mvc.xml Configuration

      <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">    <property name="webBindingInitializer">        <bean class="com.lannong.api.www.binder.MyWebBindingInitializer"/>    </property>    <!-- others config --></bean>
Local configuration Add the conversion method to the controller and add the @initbinder
    • Code

      @InitBinderpublic void initBinder(WebDataBinder webDataBinder) throws Exception{    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");    simpleDateFormat.setLenient(false);    webDataBinder.registerCustomEditor(Date.class , new CustomDateEditor(simpleDateFormat , true));}或@InitBinderpublic void initBinder(WebDataBinder binder, WebRequest request) {    binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {        @Override        public void setAsText(String text) {            setValue(DateTimeUtil.string2Date(text, "yyyy-MM-dd"));        }    });}

Both ways are possible, and the scope is the same as that of the method scope

Use @datetimeformat (pattern = "YYYY-MM-DD")

Annotations can be added to attributes, or they can be added to a method and need to be imported into Joda-time.jar. In addition, the format of the date parameter needs to be consistent with the Patten definition, otherwise 400 error will be reported

Spring MVC parameter Type conversions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.