`

springmvc参数类型转换三种方式

 
阅读更多

SpringMVC绑定参数之类型转换有三种方式:

    1. 实体类中加日期格式化注解

   

@DateTimeFormat(pattern="yyyy-MM-dd hh:MM")
private Date creationTime;
    2.在Controller类的方法中加入一段代码

 

    /**
     * 在controller层中加入一段数据绑定代码
     * @param webDataBinder
     */
    @InitBinder
    public 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));
    }
   备注:自定义类型转换器必须实现PropertyEditor接口或者继承PropertyEditorSupport类
写一个类 extends propertyEditorSupport(implements PropertyEditor){
     public void setAsText(String text){
         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy -MM-dd hh:mm");
        Date date = simpleDateFormat.parse(text);
        this.setValue(date);
     }
     public String getAsTest(){
      Date date = (Date)this.getValue(); 
      return this.dateFormat.format(date);
     }
}
   3.(spring 3.0以前使用正常,以后的版本需要使用<mvc:annotation-driven/>注册使用)使用xml配置实现类型转换(系统全局转换器)
   1.注册conversionservice
  
        <!-- 注册ConversionService-->
        <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
            <property name="converters">
                <set>
                    <bean class="com.ezubo.global.portal.util.StringToDateConverter">
                        <constructor-arg index="0" value="yyyy-MM-dd hh:mm"/>
                    </bean>
                </set>
            </property>
        </bean>
 备注:StringtoDateConverter.java的实现:
/**
 * Created by 苏 on 15-10-13.
 */
public class StringToDateConverter implements Converter<String,Date> {

    private static final Logger logger = LoggerFactory.getLogger(StringToDateConverter.class);

    private String pattern;

    public StringToDateConverter(String pattern){
        this.pattern = pattern;
    }

    public Date convert(String s) {

        if(StringUtils.isBlank(s)){
            return null;
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        simpleDateFormat.setLenient(false);
        try{
            return simpleDateFormat.parse(s);
        }catch(ParseException e){
            logger.error("转换日期异常:"+e.getMessage() , e);
            throw new IllegalArgumentException("转换日期异常:"+e.getMessage() , e);
        }
    }
}
   2.使用 ConfigurableWebBindingInitializer 注册conversionService
       <!--使用 ConfigurableWebBindingInitializer 注册conversionService-->
       <bean id="webBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
            <property name="conversionService" ref="conversionService"/>
       </bean>
 3.注册ConfigurableWebBindingInitializerRequestMappingHandlerAdapter
       <!-- 注册ConfigurableWebBindingInitializer 到RequestMappingHandlerAdapter-->
       <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
            <property name="webBindingInitializer" ref="webBindingInitializer"/>
            <!-- 线程安全的访问session-->
            <property name="synchronizeOnSession" value="true"/>
       </bean>
 

此时可能有人会问,如果我同时使用 PropertyEditor 和 ConversionService,执行顺序是什么呢?内部首先查找PropertyEditor 进行类型转换,如果没有找到相应的 PropertyEditor 再通过 ConversionService进行转换。

   4.(spring 3.2以后使用正常)使用<mvc:annotation-driven/>注册conversionService

   具体原因请参考:

                SpringMVC配置全局日期转换器,处理日期转换异常

      1.注册ConversionService

 

        <!-- 注册ConversionService-->
        <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
            <property name="converters">
                <set>
                    <bean class="com.ezubo.global.portal.util.StringToDateConverter">
                        <constructor-arg index="0" value="yyyy-MM-dd hh:mm"/>
                    </bean>
                </set>
            </property>
        </bean>

  2.需要修改springmvc-servlet xml配置文件中的annotation-driven,增加属性conversion-service指向新增的   conversionService。

    <mvc:annotation-driven conversion-service="conversionService">
        <mvc:message-converters register-defaults="true">
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
                <!--转换时设置特性-->
                <property name="features">
                    <array>
                        <!--避免默认的循环引用替换-->
                        <ref bean="DisableCircularReferenceDetect"/>
                        <ref bean="WriteMapNullValue"/>
                        <ref bean="WriteNullStringAsEmpty"/>
                        <ref bean="WriteNullNumberAsZero"/>
                    </array>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

 

分享到:
评论

相关推荐

    SpringMVC数据类型转换超详细介绍

    本文将详细介绍SpringMVC中数据类型转换的具体实现方式及其背后的工作原理。 #### 二、Spring 3之前的类型转换与验证 在Spring 3之前,类型转换主要依赖于`PropertyEditor`接口。`PropertyEditor`负责将字符串转换...

    SpringMVC后台接收请求参数的几种方式Demo

    本教程将详细解析Spring MVC后台接收请求参数的多种方式。我们将重点关注GET和POST请求,这两种请求方式在Web开发中最为常见。以下是对每种方式的详细说明: 1. **路径变量(Path Variables)** 在Spring MVC中,...

    专题资料(2021-2022年)SpringMVC数据类型转换要点.doc

    【SpringMVC数据类型转换要点】专题资料详细解析 在SpringMVC中,数据类型转换、验证和格式化是Web应用程序开发中不可或缺的部分。在早期的Spring版本中,这一过程主要依赖于`PropertyEditor`来完成,但这种方法...

    SpringMVC-8 数据类型转换、数据格式化与数据校验

    在Spring MVC框架中,数据类型转换、数据格式化和数据校验是开发Web应用程序时不可或缺的部分。这些功能有助于确保从客户端接收到的数据准确无误,同时提供了一种优雅的方式来处理和展示这些数据。本篇文章将深入...

    SpringMVC实现自定义类型转换器

    SpringMVC实现自定义类型转换器 SpringMVC框架提供了强大的类型转换功能,以便将HTTP请求参数转换成Java对象。但是,默认情况下,SpringMVC只能转换基本数据类型,如String转换成Integer、Double等。如果需要将...

    SpringMVC数据绑定及数据类型转换

    **数据绑定**是SpringMVC中的一种机制,允许我们将用户通过表单或其他方式提交的请求参数自动绑定到控制器中的方法参数或者模型对象的属性上。这种绑定过程极大地简化了开发者的工作,无需手动从请求中获取每个参数...

    springmvc类型转换.md

    #### 三、自定义`PropertyEditor`实现类型转换 除了使用内置的类型转换功能外,还可以通过实现`PropertyEditor`接口来自定义类型转换逻辑。下面是一个简单的示例: ```java import java.text.SimpleDateFormat; ...

    springmvc各种参数绑定

    Spring MVC通过一系列预定义的解析器,如`RequestParamMethodArgumentResolver`、`PathVariableMethodArgumentResolver`等,来解析和绑定不同的参数类型。当控制器方法被调用时,Spring MVC会遍历这些解析器,直到...

    springMVC三种数据转换的Demo

    `CustomEditor`是Spring MVC提供的一种早期的数据转换方式,主要用于简单的类型转换。我们可以通过注册自定义的`PropertyEditor`来处理特定类型的转换。首先,我们需要创建一个继承自`PropertyEditorSupport`的类,...

    解决springmvc关于前台日期作为实体类对象参数类型转换错误的问题

    解决SpringMVC关于前台日期作为实体类对象参数类型转换错误的问题有多种方法,下面我们将介绍三种解决方案。 解决方案1:使用@DateTimeFormat注解 在对应的实体类属性上加入@DateTimeFormat(pattern = "yyyy-MM-dd...

    SpringMVC接收请求参数所有方式总结

    本文将全面总结SpringMVC接收请求参数的所有方式,并探讨其背后的工作机制。 1. GET方法请求参数处理: 当使用GET方法发送请求时,参数通常附加在URL中。通过`@RequestParam`注解可以轻松地将这些参数绑定到控制器...

    Springmvc请求处理方法参数

    自动类型转换 Spring MVC会尝试自动将请求参数的字符串值转换为目标类型。例如,将字符串"123"转换为整型123。如果转换失败,Spring MVC会抛出异常。 ### 5. 请求头参数 除了请求参数,我们还可以通过`@Request...

    springmvc注解式控制器的数据验证、类型转换及格式化 SpringMVC数据验证

    总结来说,Spring MVC的注解式控制器提供了强大的数据验证、类型转换和格式化功能,简化了Web开发过程,提升了应用的安全性和用户体验。通过合理利用这些特性,开发者可以构建更加健壮、易于维护的Web应用。

    springmvc 参数绑定例子1

    - **控制器方法签名**:控制器方法的参数可以是基本类型、对象或数组,Spring MVC会尝试将请求参数与这些参数进行匹配。 - **注解驱动**:Spring MVC使用注解如`@RequestParam`、`@PathVariable`、`@ModelAttribute...

    Springmvc自定义参数转换实现代码解析

    SpringMVC 提供了多种参数绑定的方式,包括默认的参数绑定、简单类型参数绑定、POJO 类型参数绑定、包装类型参数绑定等,除此之外还提供了自定义参数转换的功能,允许开发者根据需求实现自定义的参数转换。

    Http请求传参SpringMVC接收参数详细解析

    问题2:前端参数未转换为JSON格式,会导致403错误。需使用`JSON.stringify()`将JavaScript对象转化为JSON字符串。 3. 传数组参数 在POST请求中,可以使用@RequestParam接收数组。当数组作为请求参数时,需要在参数...

    SpringMVC参数绑定

    以上知识点详细解释了SpringMVC参数绑定的机制、实现方式和一些高级特性,这在开发基于SpringMVC的Web应用程序时是必不可少的技能。掌握这些知识点有助于开发者更好地处理HTTP请求和响应,以及在Java Web开发中实现...

    springMvc集合接收参数的用法

    通过合理使用`@RequestBody`和`@ModelAttribute`注解,以及适当的参数类型,你可以轻松地处理包括集合在内的复杂数据结构。在实际开发中,确保前端和后端的参数命名一致,以便Spring MVC能够正确地进行数据绑定。...

Global site tag (gtag.js) - Google Analytics