实现方式以字符串转Date为例说明:

全局配置

第一种:实现 Converter 接口

  • 实现类: 
    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配置

    <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>
    </property>
    </bean>
  • 配置到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>

第二种:实现Formatter接口,与第一种实现方式类似

  • 实现类

    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配置

    <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>

第三种:实现WebBindingInitializer接口

  • 实现类

    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配置

    <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>

局部配置

在Controller中添加转换方法并添加@InitBinder

  • 代码

    @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));
    } 或 @InitBinder
    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"));
    }
    });
    }

两种方式都可以,作用域和该方法作用域一样

使用@DateTimeFormat(pattern = "yyyy-MM-dd")

注解可以加在属性上,也可以加在方法上,需要导入joda-time.jar。另外日期参数的格式需要和patten定义的一致,否则会报400错误

spring mvc 参数类型转换的更多相关文章

  1. Spring mvc参数类型转换

    1,需求 有时候我们接收到的参数为String类型的,但是我们需要将它们转化为其他类型的如:date类型,枚举类型等等,spring mvc为我们提供了这样的功能. 2,配置文件 在springmvc ...

  2. spring mvc: 参数方法名称解析器(用参数来解析控制器下的方法)MultiActionController/ParameterMethodNameResolver/ControllerClassNameHandlerMapping

    spring mvc: 参数方法名称解析器(用参数来解析控制器下的方法)MultiActionController/ParameterMethodNameResolver/ControllerClas ...

  3. spring mvc 参数

    Struts(表示层)+Spring(业务层)+Hibernate(持久层) Struts: Struts是一个表示层框架,主要作用是界面展示,接收请求,分发请求. 在MVC框架中,Struts属于V ...

  4. spring mvc参数绑定

    spring绑定参数的过程 从客户端请求key/value数据,经过参数绑定,将key/value数据绑定到controller方法的形参上.springmvc中,接收页面提交的数据是通过方法形参来接 ...

  5. Spring MVC参数封装传递

    在Spring MVC中,前端JSP页面可以传递  基本类型(int,String).实体类型.包装类型.数组类型.集合类型(List.map )等. 假如在传递的类型中有 Date类型的字段,需要在 ...

  6. spring mvc 参数绑定

    基础类型 原始类型:id必须要传,否则报错. @RequestMapping("/test") @ResponseBody public ResponseData test(int ...

  7. Spring MVC 参数必填项导致客户端报 HTTP 400 并且无法进入断点的问题

    1.问题 Spring MVC 在参数上设置了必填项,post 请求时报 HTTP 400 并且未进入断点,如将“年龄”设置为了必填项: @RequestParam( value="age& ...

  8. Spring MVC 参数的绑定方法

    在Spring MVC中,常见的应用场景就是给请求的Url绑定参数.本篇就介绍两种最最基本的绑定参数的方式: 基于@RequestParam 这种方法一般用于在URL后使用?添加参数,比如: @Req ...

  9. Spring MVC参数处理

    使用Servlet API作为参数 HttpServletRequest HttpServletResponse HttpSession 使用流作为参数 总结 Spring MVC通过分析处理处理方法 ...

随机推荐

  1. WORD添加批注(JAVA)

    import com.spire.doc.*;import com.spire.doc.documents.CommentMark;import com.spire.doc.documents.Com ...

  2. Python2.7 报错:UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-4: ordinal not in range(128)

    一. 错误原因(网上找的是这样说的,具体的我也不是很了解2.7版本的编码问题): 1.python默认使用ASCII处理字符流. 2.Unicode编码与ASCII编码的不兼容,Python脚本文件是 ...

  3. (2)ESP8266 矩阵的逆求解

    #include "math.h" int N=4; int M=4; float a[4][4]={ {1,0,0,0}, {1,0.5,0,0}, {1,0,1,0}, {1, ...

  4. LeetCode 1043. Partition Array for Maximum Sum

    原题链接在这里:https://leetcode.com/problems/partition-array-for-maximum-sum/ 题目: Given an integer array A, ...

  5. SpringBoot之使用Druid连接池,SQL监控和spring监控

    项目结构 1.引入maven依赖 <dependencies> <dependency> <groupId>org.springframework.boot< ...

  6. ES6 数组方法 forEach map filter find every some reduce

    1. forEach const colors = ['red', 'blue', 'green'] colors.forEach(function (params) { console.log(pa ...

  7. OpenFOAM——设置自定义非均匀场区域

    在使用OpenFOAM进行计算的时候,我们需要对计算域设置非均匀场,比如最典型的溃坝算例,在开始计算以前,我们需要首先设定某一区域的水的体积分数为1,就是下面这样的: 有可能我们在计算传热问题的时候, ...

  8. OpenFOAM——90度T型管

    本算例来自<ANSYS Fluid Dynamics Verification Manual>中的VMFL010: Laminar Flow in a 90° Tee-Junction. ...

  9. ICEM-缺口圆柱

    原视频下载地址:https://pan.baidu.com/s/1bpahxd9 密码: bpp7

  10. spring boot eclipse 远程调试

    <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot ...