java - Spring:将字符串从 View 转换为日历对象

标签 java spring jsp spring-mvc

如何将字符串从表单输入(如果是 easyui-datetimebox)转换为 Controller 中对象中的日历属性,由 Spring 自动绑定(bind)?

我读过 http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/validation.html但我在那儿找不到任何恰到好处的内容。

JSP:

<input id="DeadLineDate"
  class="easyui-datetimebox" 
  name="DeadLineDate"
  value="${SessionDeadLineDate}"
  data-options="formatter:myformatter,
                parser:myparser
/>

提交时,Spring验证抛出错误:

Failed to convert property value of type java.lang.String to required type java.util.Calendar for property DeadLineDate; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Calendar] for property DeadLineDate: no matching editors or conversion strategy found.

附言: Spring 3

编辑:添加 Controller 的方法来执行操作:

@Controller
@RequestMapping("/project/MaintainProjectFrm")
@SessionAttributes({"project","SessionDeadLineDate"})
public class MaintainProjectController {

    /* ... many methods... */

    @RequestMapping(params = "update", method = RequestMethod.POST, produces={"text/plain; charset=UTF-8"})
    public String update(@ModelAttribute("project") Project project, 
                            BindingResult result, 
                                    SessionStatus status, 
                                        ModelMap model,
                                            HttpServletRequest req,
                                                HttpServletResponse resp) throws IOException {

        projectValidator.validate(project, result);

        if (result.hasErrors()) {
             //has errors, in this case, that one shown in text above, which is rendered again in view (JSP)
            return "/project/MaintainProjectFrm";
        } else {

            try{
                mpService.updateProject(project);
            }
            catch(Exception e){
                resp.setStatus(500);
                resp.getWriter().write("Error updating project: " + e.getMessage());
                return "/project/MaintainProjectFrm";
            }

            status.setComplete();

        }
    }

    /* ... yet other methods ... */
}

最佳答案

我假设您的 Project 类具有字段 DeadLineDate(字段应以小写字符开头)。

像这样用@DateTimeFormat注释

@DateTimeFormat(pattern = "yyyy/MM/dd") // or whatever pattern you want
private Calendar DeadLineDate;

然后您的客户端将需要发送适当的模式。

关于java - Spring:将字符串从 View 转换为日历对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21260209/

相关文章:

java - 时间格式中的毫秒和纳秒

java - Java SWT GridLayout 可以从右到左布局小部件吗?

java - 通用异常 :Connection timed out while using restTemplate

java - 未找到 bean NoSuchBeanDefinitionException

javascript - 在jsp页面中隐藏div标签

java - Servlet的反射(reflection),Httpservletrequest类型正在获取RequestFacade类型并且无法调用方法

java - Firebase Auth 在单击按钮时未启动 Activity 但在关闭并重新打开应用程序时有效

java - Projection.toPixels 空指针...有帮助吗?

java - Spring MVC 表单验证 : how to make field optional?

eclipse - 使用 Tomcat 和 JSP 文件不会编译