实现方式以字符串转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. fitnesse如何编辑用例

    1.测试代码: 2.编写用例 (1)新建目录 点击“edit”,编辑内容: !1 测试 * '''[[算法][TestDemo]]''' * '''[[算法2][TestDemo2]]''' 上面的第 ...

  2. LeetCode 1039. Minimum Score Triangulation of Polygon

    原题链接在这里:https://leetcode.com/problems/minimum-score-triangulation-of-polygon/ 题目: Given N, consider ...

  3. c++处理字符串string.find()与string::npos

    1. string s  = “xxx”; int a = s.find(‘x’); 如果没有匹配到,那么a = string::npos;

  4. 如何把上传图片时候的文件对象转换为图片的url !

    getObjectURL(file) { var url = null; if (window.createObjectURL != undefined) { url = window.createO ...

  5. win7虚拟机安装

    https://blog.csdn.net/qq_16503045/article/details/81904986 iso下载地址 https://msdn.itellyou.cn/

  6. python 微服务开发书中几个方便的python框架

    python 微服务开发是一本讲python 如果进行微服务开发的实战类书籍,里面包含了几个很不错的python 模块,记录下,方便后期回顾学习 处理并发的模块 greenlet && ...

  7. [CSP-S 2019]括号树

    [CSP-S 2019]括号树 源代码: #include<cstdio> #include<cctype> #include<vector> inline int ...

  8. 洛谷 P1351 联合权值 题解

    P1351 联合权值 题目描述 无向连通图 \(G\) 有 \(n\) 个点,\(n-1\) 条边.点从 \(1\) 到 \(n\) 依次编号,编号为 \(i\) 的点的权值为 \(W_i\)​,每条 ...

  9. P1071 潜伏者

    //Pro:NOIP2009 T1 P1071 潜伏者 #include<iostream> #include<cstdio> #include<cstring> ...

  10. Spark-Streaming DirectKafka count 案例

    Spark-Streaming DirectKafka count 统计跟直接 kafka 统计类似,只不过这里使用的是 Direct 的方式,Direct方式使用的 kafka 低级API,不同的地 ...