无法从HTML标记输入类型日期,Spring MVC获取值

时间:2015-09-13 15:26:27

标签: java spring jsp spring-mvc binding

为什么输入类型date html标签的值没有应用于相应的对象设置器?

换句话说:当我在下面的html字段中输入日期时:

 <form:input path="dateOfBirth" type="date" name="date" id="date" max="09/09/2015"/>

然后在以下方法中设置一个断点:

System.out.println(customer.getFirstName());

并寻找

customer.getBirthDate()

后者返回null

以下是Customer object

public class Customer implements Serializable {

    @Temporal(TemporalType.DATE)
    @Column (name = "date_of_birth")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date dateOfBirth;

// all getters/setter are being defined + hashCode()+equals()
}

这是我的JSP表单:

<form:form class="pure-form pure-form-aligned"
           action="/register"
           method="post"
           onsubmit="return validateUserInput();"
           modelAttribute="user">

    <fieldset>
            <%--Date of birth--%>
        <div class="pure-control-group">
            <label for="date">Date of birth</label>
            <form:input path="dateOfBirth" type="date" name="date" id="date" max="09/09/2015"/>
            <label id="errorDate" style="width: auto"></label>
        </div>

    </fieldset>
</form:form>

我的处理注册过程的控制器:

@Controller
@RequestMapping(value = "/register")
public class UserRegistrationController {
    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private CustomerService customerService;


    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
        binder.registerCustomEditor(Date.class, editor);
        binder.registerCustomEditor(CustomerTypeEditor.class, new CustomerTypeEditor());
    }


    @ModelAttribute("customertypes")
    public List<CustomerType> customerTypes() {
        return customerService.getCustomerRepository().getCustomerTypes();
    }

    @RequestMapping(method = RequestMethod.GET)
    public String displayRegistrationForm(Model model) {
        model.addAttribute("user", new Customer());
        return "register";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processUserRegistration(@ModelAttribute Customer customer) {
        System.out.println(customer.toString());
        System.out.println(customer.getFirstName());
        customerRepository.insert(customer);
        return "redirect:/dashboard";
    }
}

重新解释上述问题:当我按下提交按钮时,日期值将被插入customer.setDateOfBirth(Date date)。我该如何解决这个问题?

0 个答案:

没有答案