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

一、实体类中加日期格式化注解

@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date createTime;

此种方式最简便,但是作用范围是局部的,只对对应的controller起作用

二、属性编辑器

在Spring3.1之前可以使用@InitBinder实现。
自定义springMVC的属性编辑器主要有两种方式:

  • 一种是使用@InitBinder标签在运行期注册一个属性编辑器,这种编辑器只在当前Controller里面有效;
  • 还有一种是实现自己的 WebBindingInitializer,然后定义一个AnnotationMethodHandlerAdapter的bean,在此bean里面进行注册 ,这种属性编辑器是全局的。

1.使用@InitBinder

WebDataBinder是用来绑定请求参数到指定的属性编辑器.由于前台传到controller里的值是String类型的,当往Model里Set这个值的时候,如果set的这个属性是个对象,Spring就会去找到对应的editor进行转换,然后再SET进去。
initBinder:

    /**
     * 在controller层中加入一段数据绑定代码
     * @param webDataBinder 必须有该参数WebDataBinder
     */
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        simpleDateFormat.setLenient(false);
        webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(simpleDateFormat, true));
    }

springmvc.xml:

  
  
      
          
              
          
      
  
  

或者:


    
        
            
        
    

2.实现自己的 WebBindingInitializer

package com.hcx.controller;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* 自定义属性编辑器
* Created by hongcaixia on 2020/1/10.
*/
public class MyPropertyEditor extends PropertyEditorSupport{

   private String dateFormat="yyyy-MM-dd";

   @Override
   public void setAsText(String text){
       SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy -MM-dd hh:mm");
       Date date = null;
       try {
           date = simpleDateFormat.parse(text);
           this.setValue(date);
       } catch (ParseException e) {
           e.printStackTrace();
       }
   }

   public void setDateFormat(String dateFormat) {
       this.dateFormat = dateFormat;
   }

}

在springMVC的配置文件里面定义一个AnnotationMethodHandlerAdapter,并设置其WebBindingInitializer属性为我们自己定义的WebBindingInitializer对象:

  
        
        
            
        
    

三、类型转换器Converter

jsp:

    
用户名:
年龄:
生日:

user:

@Data
@ToString
public class User {
    private String name;
    private String age;
    private Date birthday;
}

controller:

    @RequestMapping("/saveUser")
    public String saveUser(User user){
        //User(name=极多人小红, age=23, birthday=Sun Dec 11 00:00:00 CST 1994)
        System.out.println(user);
        return "success";
    }

日期格式:
2019/02/12能自动接收
2019-02-12报错:


image.png

第一步:编写自定义类型转换器
DateConverter :

package com.hcx.utils;

import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by hongcaixia on 2020/1/10.
 */
public class DateConverter implements Converter{

    @Nullable
    @Override
    public Date convert(String s) {
        if(s==null){
            throw new RuntimeException("数据不能为空");
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return dateFormat.parse(s);
        } catch (ParseException e) {
            throw new RuntimeException("数据类型转换异常");
        }
    }
}

第二步:配置自定义类型转换器
springmvc.xml




    
    

    
    
        
        
        
        
    

    
    
        
            
                
                
            
        
    

    
    

image.png

你可能感兴趣的:(SpringMVC绑定参数之类型转换的三种方式)