spring mvc 参数类型转换

实现方式以字符串转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错误

原文地址:https://www.cnblogs.com/f-anything/p/8707495.html

时间: 2024-08-03 05:38:00

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

spring mvc 参数绑定

1.默认支持类型 a.HttpServletRequest b.HttpServletResponse c.HttpSession e.Model/ModelMap model是接口,modelmap是接口实现.将model数据填充到request域 2.简单类型 a.直接在controller上加上形参 这种方式,链接中可以不传入定义的参数或为空,不会报错.如果要正常使用,则请求过来的参数,必须与形参名一致. b.使用@RequestParam 3.pojo类型 对应表单提交 请求过来的的参数

Spring MVC 之类型转换(五)

虽然SpringMVC可以自动绑定多种数据类型,但是有时候有些特殊的数据类型还是会在绑定时发生错误,需要我们自己书写类型转换完成绑定. SpringMVC中提供两种绑定方式:以时间转换为例. 1.属性编辑器(传统方式) 控制器: 1 @RequestMapping(value="/login.do") 2 public String login(UserBean user){ 3 log.info(user.getUsername()); 4 log.info(user.getBirt

Spring MVC 参数校验

转自:http://blog.csdn.net/eson_15/article/details/51725470 这一篇博文主要总结一下springmvc中对数据的校验.在实际中,通常使用较多是前端的校验,比如页面中js校验,对于安全要求较高的建议在服务端也要进行校验.服务端校验可以是在控制层conroller,也可以是在业务层service,controller校验页面请求的参数的合法性,在服务端控制层conroller的校验,不区分客户端类型(浏览器.手机客户端.远程调用):service层

Java之Spring mvc详解

文章大纲 一.Spring mvc介绍二.Spring mvc代码实战三.项目源码下载四.参考文章 一.Spring mvc介绍 1. 什么是springmvc   springmvc是spring框架的一个模块,springmvc和spring无需通过中间整合层进行整合.springmvc是一个基于mvc的web框架. 2. mvc设计模式在b/s系统 下的应用 3. Spring mvc框架执行流程   第一步:发起请求到前端控制器(DispatcherServlet)  第二步:前端控制器

spring mvc关于jsp页面传递到controller层参数类型转换(格式化)的学习记录--2018年1月

spring mvc jsp传递参数到controller涉及到日期类型数据,需要使用到类型转换器:目前笔者找到两种类型转换器可以使用: 类型一:实现Convert<Source,Target>接口的方式(Source源数据,Target目标数据类型),实现功能是一种数据类型到另一种数据类型:数据转换类如下:在不添加DateTimeFormatter.ofPattern("yyyy/MM/dd")时(MM必须大写,小写表示时间分),默认需要输入的String样式"

Spring MVC请求参数绑定

所谓请求参数绑定,就是在控制器方法中,将请求参数绑定到方法参数上 @RequestParam 绑定单个请求参数到方法参数上 @RequestParam("id") Integer id 将请求参数名为id的变量,绑定到id参数上,如果不知道@RequestParam值,默认从请求参数中取和变量名相同的请求参数 @RequestParam(value = "id",required = false) Integer id 可以通过指定required参数来指定是否必须

Spring MVC JSON自定义类型转换(续)

前面提到了两种转换类型的方法(Spring MVC JSON自定义类型转换),这里针对Json转换提供一种更简便的方法. 通过配置全局的日期转换来避免使用麻烦的注解. 首先用到了一个简单的日期工具类DateUtil.java /** * DateUtil类 * * @author liuzh */ public class DateUtil { public static final String Y_M_D = "yyyy-MM-dd"; public static final St

Spring MVC JSON 实现JsonSerializer Date类型转换

转载至:http://blog.csdn.net/lantianzhange/article/details/40920933 在Spring MVC中存在两大类的类型转换,一类是Json,一个是Spring的Binder转换. JSON: 使用Json转换时,可以如下使用: [java] view plaincopyprint? public class Test { private Date createdate; @JsonSerialize(using = DateYMDHMSJsonS

Spring MVC JSON自定义类型转换

类型有很多,这里只用日期为例说明. 在Spring MVC中存在两大类的类型转换,一类是Json,一个是Spring的Binder转换. JSON: 使用Json转换时,可以如下使用: public class Test { private Date createdate; @JsonSerialize(using = DateYMDHMSJsonSerializer.class) public Date getCreatedate() { return createdate; } @JsonD