提交Spring表单时的日期格式错误

时间:2016-01-18 15:59:52

标签: forms date spring-mvc formatting thymeleaf

我有一个项目,我使用Spring MVC和Thymeleaf。 我需要根据每个用户的偏好为每个用户显示不同格式的日期。 例如,UserA希望显示像MM / dd / yyyy这样的日期,而UserB想要显示dd / MM / yyyy等日期。

为此,我使用这个百万富翁参数:

th:value="${#dates.format(myDate, dateFormat)}"

值" dateFormat"基于用户偏好。这很好。

我的问题是日期输入是一种形式,当我提交表单时,它没有采用良好的格式。我总是得到MM / dd / yyyy。

如果我选择格式dd / MM / yyyy并输入18/01/2016,在我的春季控制器中我获得" Thu Jun 01 00:00:00 CEST 2017"对应于dd / MM / yyyy的01/06/2017。

如何使用我想要的格式获取日期?

这是我的代码:

<form th:action="@{/test}" th:object="${filter}" th:method="POST">
    <input type="date" th:type="date" class="form-control" th:id="myDate"
           th:name="myDate" th:value="${#dates.format(filter.myDate, dateFormat)}"/>
</form>

控制器:

@RequestMapping(value = "/test", method = RequestMethod.POST)
public String myTest(@ModelAttribute Filter filter, Model model) {

    Systeme.out.println(model.dateFormat);
    // dd/MM/yyyy

    Systeme.out.println(filter.myDate.toString());
    // Thu Jun 01 00:00:00 CEST 2017

    return "test";
}

3 个答案:

答案 0 :(得分:7)

经过一天的研究,我发现Spring读取了Web请求中发送的值,并尝试将其与Filter对象绑定。

对于日期值,它除了找到具有“MM / dd / yyyy”格式的值。如果您使用其他格式发送值,则不起作用。

要解决此问题,可以使用注释“InitBinder”。

@InitBinder
private void dateBinder(WebDataBinder binder) {
    //The date format to parse or output your dates
    SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
    //Create a new CustomDateEditor
    CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
    //Register it as custom editor for the Date type
    binder.registerCustomEditor(Date.class, editor);
}

对每个Web请求执行此方法。在这里,我调用我的“dateFormat()”方法来获取用户首选项中的格式,并告诉Spring,它在Web请求中找到的所有java.util.Date都具有这种格式。

这是我的完整代码:

过滤:

import java.util.Date;

@lombok.Data
public class TestDateFilter {
    private Date myDate;

    public TestDateFilter() {
        this.myDate = new Date();
    }
}

控制器:

@RequestMapping(value = "/testdate")
public String testDate(Model model) {
    model.addAttribute("filter", new TestDateFilter());
    return "testdate";
}

@RequestMapping(value = "/testdate", method = RequestMethod.POST)
public String testDatePost(@ModelAttribute("filter") TestDateFilter filter, Model model) {
    System.out.printf(filter.getLoadingStartDate().toString());
    System.out.printf(dateFormat());
    return "testdate";
}

@ModelAttribute("dateFormat")
public String dateFormat() {
    return userPreferenceService.getDateFormat();
}

@InitBinder
private void dateBinder(WebDataBinder binder) {
    //The date format to parse or output your dates
    SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
    //Create a new CustomDateEditor
    CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
    //Register it as custom editor for the Date type
    binder.registerCustomEditor(Date.class, editor);
}

HTML:

    <form th:action="@{/testdate}" th:object="${filter}" th:method="POST">
        <div class="row">
            <div class="col-xs-12 col-sm-6">
                <div class="input-group date">
                    <input type="date" th:type="date" class="form-control"
                           th:id="loadingStartDate" th:name="loadingStartDate"
                           th:value="${#dates.format(filter.loadingStartDate, dateFormat)}" />
                </div>
            </div>
        </div>
        <div class="row">
            <div class="form-group">
                <div class="col-xs-12 col-sm-12">
                    <button type="submit" class="btn btn-primary btn-lg pull-right">
                        submit
                    </button>
                </div>
            </div>
        </div>
    </form>

答案 1 :(得分:3)

您可以注释日期属性

t2

自Spring 3.2以来没有Joda依赖

答案 2 :(得分:1)

我觉得有麻烦,因为Spring不明白输入值是Date。 你的变量myDate是java.util.Date类型吗?

如果是,请尝试注册这样的格式化程序:

package your.pack.formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.format.Formatter;

public class DateFormatter implements Formatter<Date> { 

    final String defaultDateFormat = "dd.MM.yyyy";

    @Override
    public String print(Date object, Locale locale) {
        return new SimpleDateFormat(defaultDateFormat).format(object);
    }

    @Override
    public Date parse(String text, Locale locale) throws ParseException {
        return DateUtils.parseDate(text, defaultDateFormat);
    }
}

然后在您的配置中注册:

@Configuration
public class ConversionServiceConfig extends WebMvcConfigurerAdapter {

   @Bean
   public DateFormatter dateFormatter() {
       return new DateFormatter();
   }

   @Override
   public void addFormatters(FormatterRegistry registry) {
       registry.addFormatter(dateFormatter());
   }
}

但我不知道如何让它按照你想要的方式动态运行......

用户偏好设置是存储在数据库还是属性中?

相关问题