Spring:将String从View转换为Calendar对象

时间:2014-01-21 13:57:23

标签: java spring jsp spring-mvc

如何将表单输入(easyui-datetimebox,以防万一)中的字符串转换为Controller中对象的Calendar属性,由Spring自动提取?

我读过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.

PS:Spring 3

编辑:添加控制器的方法来执行操作:

@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 ... */
}

3 个答案:

答案 0 :(得分:7)

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

使用@DateTimeFormat注释它

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

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

答案 1 :(得分:4)

您有两种可能实现此目的:您可以使用PropertyEditor

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Calendar.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(parseDate());
        }

        private Calendar parseDate() {
            try {
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
                cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));
                return cal;
            } catch (ParseException e) {
                 return null;
            }
        }
    });
}

文档see this and this.

或者您可以使用弹簧转换服务。为此,请参阅:"Spring 3 Type Conversion"

答案 2 :(得分:-1)

像Sotirios Delimanolis一样试试这个......

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

最后,将其添加到pom.xml:

<dependency>
   <groupId>joda-time</groupId>
   <artifactId>joda-time</artifactId>
   <version>2.3</version>
</dependency>