Spring MVC与表单日期提交的问题

spring mvc 本身并不提供日期类型的解析器,需要手工绑定, 否则会出现非法参数异常.

 org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.util.Date]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException

解决方法很简单,只需要在controller 里面注册一个类型解析器:

    @InitBinder
public void InitBinder(HttpServletRequest request,
ServletRequestDataBinder binder) {
// 不要删除下行注释!!! 将来"yyyy-MM-dd"将配置到properties文件中
// SimpleDateFormat dateFormat = new
// SimpleDateFormat(getText("date.format", request.getLocale()));
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, null, new CustomDateEditor(
dateFormat, true));
}

这样就ok了,

demo 如下:

controller

@RequestMapping("bakComment")
@Controller
public class BakCommentController {
Logger logger = Logger.getLogger(getClass());
@Resource
private CommentService commentService; //@InitBinder
public void InitBinder(HttpServletRequest request,
ServletRequestDataBinder binder) {
// 不要删除下行注释!!! 将来"yyyy-MM-dd"将配置到properties文件中
// SimpleDateFormat dateFormat = new
// SimpleDateFormat(getText("date.format", request.getLocale()));
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, null, new CustomDateEditor(
dateFormat, true));
} @RequestMapping("verifyComment")
public void verifyComment(@ModelAttribute("comment") TSdComment comment,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
logger.info(comment); String str = "success";
response.setCharacterEncoding("utf-8");
response.getWriter().print(str);
}
}

html:

<form:form modelAttribute="comment" class="form" method="post">
<fieldset>
<legend> 账单信息 </legend>
<table class="table" style="width: 100%;">
<tr>
<th>ID</th>
<td><input name="commentId" value="<%=uid%>"
readonly="readonly" /></td>
<th>用户ID</th>
<td><input name="restaurantId" class="easyui-validatebox"
data-options="required:true" readonly="readonly" /></td>
</tr>
<tr>
<th>商家名称</th>
<td><input name="restaurantName" readonly="readonly" /></td>
<th>创建时间</th>
<td><input name="createTime" readonly="readonly" /></td>
</tr>
<tr>
<th>消费金额</th>
<td><input name="commentSpending" /></td>
<th>抵金卷面额</th>
<td><input name="voucherDenomination" /></td>
</tr>
<tr>
<th>审核状态</th>
<td><select>
<option value="2">待检测</option>
<option value="3">已检查(通过)</option>
<option value="4">已检查(不通过)</option>
</select></td>
<th>原因</th>
<td><input name="commentRemark" /></td>
</tr>
<tr>
<th>账单</th>
<td colspan="3"><div style="width: 600px" id="commentPic"></div>
</td>
</tr>
</table>
</fieldset>
</form:form>

控制台如下:

 2014-05-23 13:32:09,514 [http-bio-8080-exec-1] INFO  [com.sd.microMsg.controller.BakCommentController] - TSdComment [commentId=11, userId=null, restaurantId=1, voucherId=null, restaurantName=笑嘻嘻, commentMlb=null, commentContext=null, commentPersonNo=null, voucherDenomination=30.0, commentSpending=300.0, commentPictureId=null, commentPraiseCount=null, commentNegativeCount=null, commentSelectCount=null, commentSubCommentCount=null, commentReContext=null, commentRemark=mohu, commentCheckedStatus=null, commentBusinessStatus=null, createType=null, createTime=Sat May 17 19:05:52 GMT+08:00 2014, lastActiveTime=null, checkedTime=null, commentTempConsumptionTopNum=null, commentTempPerCapitaConsumptionTopNum=null, commentType=null, commentMlzs=null, commentPlusMlzs=null, commentMark=null, commentSubMark=null, version=null, dtype=null]

不绑定解析器异常堆栈如下:

  org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.util.Date]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:)
at org.springframework.validation.DataBinder.applyPropertyValues(DataBinder.java:)
at org.springframework.validation.DataBinder.doBind(DataBinder.java:)
at org.springframework.web.bind.WebDataBinder.doBind(WebDataBinder.java:)
at org.springframework.web.bind.ServletRequestDataBinder.bind(ServletRequestDataBinder.java:)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.doBind(AnnotationMethodHandlerAdapter.java:)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:)
at java.lang.Thread.run(Thread.java:)
Caused by: java.lang.IllegalArgumentException
at java.util.Date.parse(Date.java:)
at java.util.Date.<init>(Date.java:)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:)
at java.lang.reflect.Constructor.newInstance(Constructor.java:)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:)
... more
-- ::, [http-bio--exec-] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'sqlSessionFactory'
五月 , :: 下午 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet [springMvc] in context with path [/prot] threw exception [Request processing failed; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: errors
Field error in object 'comment' on field 'createTime': rejected value [-- ::]; codes [typeMismatch.comment.createTime,typeMismatch.createTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [comment.createTime,createTime]; arguments []; default message [createTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createTime'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'createTime': no matching editors or conversion strategy found]] with root cause
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: errors
Field error in object 'comment' on field 'createTime': rejected value [-- ::]; codes [typeMismatch.comment.createTime,typeMismatch.createTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [comment.createTime,createTime]; arguments []; default message [createTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createTime'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'createTime': no matching editors or conversion strategy found]
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:)
at java.lang.Thread.run(Thread.java:)

Spring MVC与表单日期提交的问题的更多相关文章

  1. Spring MVC 3 表单中文提交post请求和get请求乱码问题的解决方法

    在spring mvc 3.0 框架中,通过JSP页面.HTML页面以POST方式提交表单时,表单的参数传递到对应的servlet后会出现中文显示乱码的问题.解决办法可采用spring自带的过滤技术, ...

  2. spring mvc防止表单重复提交的代码片段

    1.定义一个token接口 package com.bigbigrain.token; import java.lang.annotation.Documented; import java.lang ...

  3. spring mvc form表单提交乱码

    spring mvc form表单submit直接提交出现乱码.导致乱码一般是服务器端和页面之间编码不一致造成的.根据这一思路可以依次可以有以下方案. 1.jsp页面设置编码 <%@ page ...

  4. Spring MVC 验证表单

      在实际工作中,得到数据后的第一步就是检验数据的正确性,如果存在录入上的问题,一般会通过注解校验,发现错误后返回给用户,但是对于一些逻辑上的错误,比如购买金额=购买数量×单价,这样的规则就很难使用注 ...

  5. spring:设置映射访问路径 或 xml配置访问路径 (spring mvc form表单)

    项目hello, 在src/main/java下面建一个目录: charpter2 一.xml配置访问路径 web.xml <web-app> <display-name>Ar ...

  6. spring mvc 接收表单 bean

    spring MVC如何接收表单bean 呢? 之前项目中MVC框架一直用struts2,所以我也就按照struts2 的思维来思考 页面loginInput.jsp: <?xml versio ...

  7. 使用Spring MVC 的表单控制器SimpleFormController

    以注册过程为例,我们可能会选择继承AbstractController来实现表单的显示,继承AbstractCommandController来实现表单的处理 ,这样是可行的,但必须要维护两个控制器 ...

  8. Spring Boot (一) 校验表单重复提交

    一.前言 在某些情况下,由于网速慢,用户操作有误(连续点击两下提交按钮),页面卡顿等原因,可能会出现表单数据重复提交造成数据库保存多条重复数据. 存在如上问题可以交给前端解决,判断多长时间内不能再次点 ...

  9. Spring MVC实现防止表单重复提交(转)

    Spring MVC拦截器+注解方式实现防止表单重复提交  

随机推荐

  1. 分享我的2014年3月unity3d面试题与参考答案

    今年3月份面试unity3d游戏程序,先做的面试题,然后人事问了我几个之前游戏开发的问题,问我英语怎么样等等,介绍了公司情况和对unity3d程序的要求.之后就回来了,总共面了不到1个半小时吧.笔试答 ...

  2. python学习day3--python基础

    1.python不用声明变量的类型,运行时python自己进行判断 2.尽量不要用“+”去拼接字符串,运行时会每遇到一个“+”就开辟一块内存空间,使用如下方式进行字符串的拼接. msg=''' inf ...

  3. 【转】Log4.NET mark

    C#通过log4net进行异常记录 C#中异常的记录也有一个模板,就是log4net.多的就不说了直接看怎么用的吧. 1.引用log4net.dll. 2.实现log4net的方法. public c ...

  4. 基于AngularJS/Ionic框架开发的性能优化

    AngularJS作为强大的前端MVVM框架,虽然已经做了很多的性能优化,但是我们开发过程中的不当使用还是会对性能产生巨大影响. 下面提出几点优化的方法: 1. 使用单次绑定符号{{::value}} ...

  5. salvage 数据块打捞工具

    基本上所有数据库都是按块存储数据的,每种数据库的块都有自己有特征,我们可以找出特征,当数据库文件丢失,甚至文件系统完全损坏时,从硬盘扇区中把数据页打捞出来,从页从数据页中恢复出行数据.根据这个原理,开 ...

  6. Linux RedHat无法安装软件问题(No package gcc available. Nothing to do)

    在一个新的Linux服务器上安装nginx的时候,命令都不能解析,缺少gcc编辑器,安装gcc的命令也出错. [root@localhost ~]# yum -y install gcc Loaded ...

  7. [java学习笔记]java语言基础概述之转义字符&break&continue

    1.转义字符 \t:制表符 \n:回车 \b:退格 \r:回车 \":双引号 \\:反斜线(常用于文件路径的书写中)   windows系统中回车符其实是由两个符号组成的,\r\n linu ...

  8. json-lib-2.4.jar Bug,json字符串中value为"[value]"结构时,解析为数组,不会解析成字符串

    使用json-lib.jar 2.4进行json字符串转换为对象时发现一个bug.贴下测试代码: <dependency> <groupId>net.sf.json-lib&l ...

  9. iOS 非ARC基本内存管理系列 4-autorelease方法和@autoreleasepool

    1.autorelease 基本用法 对象执行autorelease方法时会将对象添加到自动释放池中 当自动释放池销毁时自动释放池中所有对象作release操作 对象执行autorelease方法后自 ...

  10. swing画太极图案源码

    package org.open.swing.taiji; /** * @(#)Taichi.java * * * @author * @version 1.00 2007/6/12 */ impor ...