spring MVC 控制器(controller)接收日期类型参数出现400错误

最近刚学完 spring mvc ,遇到一个问题。就是当我表单有日期类型的数据(如出生日期)提交到后台控制器时;就发生了400error;400error用简短的话来说就是请求参数类型和后台接收参数类型对不上等。

我大概一猜就知道是因为日期类型参数的问题;下面总结了一些处理 springMVC 在接收date类型参数的处理。

====方法one

  我们后台的参数用String先接收,再把string转成date。/**

     * 新增员工
     *
     * @param empVo
     * @return 返回成功标识
     */
    @RequestMapping("/empAdd")
    @ResponseBody                     //hireday 是前台表单传过来的日期
    public String empAdd(EmpVo empVo, String hireday) {

     //把字符串日期转成date格式    SimpleDateFormat format
= new SimpleDateFormat("yyyy-MM-dd"); ParsePosition position1 = new ParsePosition(0); Date hiredayDate = format.parse(hireday, position1); //分别是入职日期和出生日期 empVo.setHireDay(hiredayDate); // DateHelper.parseString(StringHelper.getBirAgeSex(empVo.getCardno()).get("birthday") // 通过身份证获取出生日期 empVo.setBirthday( DateHelper.parseString(StringHelper.getBirAgeSex(empVo.getCardno()).get("birthday"),"yyyy-MM-dd")); //状态 empVo.setStatus(1); //默认密码 empVo.setPassword("123456"); emp.save(empVo); return "success"; }

====方法two

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

@DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date hireDay;//入职日期

@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
    public Date getHireDay() {
        return hireDay;
    }

====方法three(推荐

  控制器加入日期数据绑定方法

//将字符串转换为Date类
    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //转换日期格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //注册自定义的编辑器
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        
    }

====方法four

  实现全局日期类型转换器并进行配置

  设计日期转换类

package com.xueqing.demo;
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;
 
public class DateEdtor implements WebBindingInitializer {   
    public void initBinder(WebDataBinder binder, WebRequest request) {
        // TODO Auto-generated method stub
        //转换日期格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}

在spring MVC配置文件进行配置

<!-- 配置全局日期转换器 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">    
            <bean class="nuc.ss.wlb.core.web.DateEdtor"/>
        </property>
    </bean>

  

  

猜你喜欢

转载自www.cnblogs.com/268lwc/p/12127948.html