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

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]

 

 

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

 1  org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.util.Date]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException
 2     at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
 3     at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:198)
 4     at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:470)
 5     at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:516)
 6     at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1119)
 7     at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:924)
 8     at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
 9     at org.springframework.validation.DataBinder.applyPropertyValues(DataBinder.java:692)
10     at org.springframework.validation.DataBinder.doBind(DataBinder.java:588)
11     at org.springframework.web.bind.WebDataBinder.doBind(WebDataBinder.java:191)
12     at org.springframework.web.bind.ServletRequestDataBinder.bind(ServletRequestDataBinder.java:112)
13     at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.doBind(AnnotationMethodHandlerAdapter.java:785)
14     at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:813)
15     at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:367)
16     at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
17     at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
18     at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
19     at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
20     at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
21     at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
22     at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
23     at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
24     at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
25     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
26     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
27     at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
28     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
29     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
30     at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
31     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
32     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
33     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
34     at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
35     at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
36     at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
37     at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
38     at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
39     at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
40     at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
41     at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
42     at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
43     at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
44     at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
45     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
46     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
47     at java.lang.Thread.run(Thread.java:745)
48 Caused by: java.lang.IllegalArgumentException
49     at java.util.Date.parse(Date.java:615)
50     at java.util.Date.<init>(Date.java:272)
51     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
52     at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
53     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
54     at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
55     at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
56     ... 45 more
57 2014-05-23 13:25:52,323 [http-bio-8080-exec-1] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean sqlSessionFactory
58  五月 23, 2014 1:25:52 下午 org.apache.catalina.core.StandardWrapperValve invoke
59 严重: 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: 1 errors
60 Field error in object comment on field createTime: rejected value [2014-05-17 19:05:52]; 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
61 org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
62 Field error in object comment on field createTime: rejected value [2014-05-17 19:05:52]; 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]
63     at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:818)
64     at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:367)
65     at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
66     at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
67     at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
68     at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
69     at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
70     at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
71     at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
72     at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
73     at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
74     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
75     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
76     at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
77     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
78     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
79     at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
80     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
81     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
82     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
83     at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
84     at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
85     at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
86     at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
87     at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
88     at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
89     at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
90     at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
91     at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
92     at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
93     at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
94     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
95     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
96     at java.lang.Thread.run(Thread.java:745)

 

Spring MVC与表单日期提交的问题,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。