【问题标题】:Spring: Convert String from View to a Calendar ObjectSpring:将字符串从视图转换为日历对象
【发布时间】:2014-01-21 13:57:22
【问题描述】:

如何将表单输入中的字符串(easyui-datetimebox,以防万一)转换为控制器中对象中的日历属性,由 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:春季 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 ... */
}

【问题讨论】:

  • 我们可以看看你的处理方法吗?
  • @SotiriosDelimanolis:当然,完成!
  • 我会使用 @RequestParam 从视图中接收 DeadLineDate,并在其上手动创建一个 Calendar 对象,更新 Project 对象。但这当然不是优雅的方式!我想知道 Spring 是否能够从这个属性自动绑定日历。

标签: java spring jsp spring-mvc


【解决方案1】:

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

像这样用@DateTimeFormat注释它

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

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

【讨论】:

  • 优秀!!!我期待更多像@gregor 写的那样,但绝对是最简单的方法。 Spring具有这种灵活性真是太好了。是的,我肯定在使用 java 模式。从葡萄牙语翻译东西名称时,我的属性“大写错误”。非常感谢!
  • 好方法!
【解决方案2】:

您有两种可能实现此目的:您可以使用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 thisand this.

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

【讨论】:

  • 感谢您的回答(我已投赞成票)。但我更喜欢使用 Sotirios Delimanolis 方法,这是我案例中最简单的解决方案。问候!
  • @Alex:接受的解决方案是否适用于 spring 3.1?就我而言,这个答案救了我!谢谢格雷戈。 +1
  • @sarwar026,我实际上正在升级到 Spring 3.6,但我还无法测试它。
  • @Alex:我明白了。我也会尝试升级我的。谢谢!
【解决方案3】:

像 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-15
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 2020-05-21
    • 2020-11-30
    相关资源
    最近更新 更多