在上面的例子中,我们运行时,将会看到的是页面是报错的。为了查看详细的信息,我们可以在application.properties中添加logging.level.org.springframework.web=DEBUG这一行的代码。这个时候我们运行时,看到的debug的信息如下:
对于为什么会这样,我们有必要去看一下Spring中的DateTimeFormatterRegistrar的类。在这个类中,你会看到,这里配置了解析和打印JRS310。也就是说,这里规定的日期的格式,在美国所用的格式是MM/dd/yy,而在其它地方用的是dd/MM/yy的格式。所以我们需要在Spring启动时,将自己用到的格式预置好。
1.创建日期格式
你们在项目下创建 一个包,包的名字叫date,同时日期需要转换的类叫USLocationDateFormatter.
package masterSpringMVC.date;
import org.springframework.format.Formatter;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
/**
* 根据本地的国家,判断用什么样的日期
* Created by OwenWilliam on 2016/5/15.
*/
public class USLocalDateFormatter implements Formatter<LocalDate> {
/**美国的日期格式*/
public static final String US_PATTERN = "MM/dd/yyyy";
/**其它国家的日期格式*/
public static final String NORMAL_PATTERN = "dd/MM/yyyy";
/**
* 语法上的解析
* @param text
* @param locale
* @return
* @throws ParseException
*/
@Override
public LocalDate parse(String text, Locale locale) throws ParseException {
return LocalDate.parse(text, DateTimeFormatter.ofPattern(getPattern(locale)));
}
/**
* 将locale转换为String
* @param object
* @param locale
* @return
*/
@Override
public String print(LocalDate object, Locale locale) {
return DateTimeFormatter.ofPattern(getPattern(locale)).format(object);
}
/**
* 判断本地是美国,还是其它国家
* @param locale
* @return
*/
public static String getPattern(Locale locale)
{
return isUnitedStates(locale) ? US_PATTERN : NORMAL_PATTERN;
}
/**
* 是否是美国
* @param locale
* @return
*/
private static boolean isUnitedStates(Locale locale)
{
return Locale.US.getCountry().equals(locale.getCountry());
}
}
2.创建WEB的构造器
同样我们在项目下创建一个config的包,同时创建 一个WebConfiguration的类。这个类将会继承WebMvcConfigurerAdapter, Spring要构造会以我们的日期格式来构造的。
package masterSpringMvc.config;
import masterSpringMvc.dates.USLocalDateFormatter;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.
WebMvcConfigurerAdapter;
import java.time.LocalDate;
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Override public void addFormatters(FormatterRegistry registry) {
registry.addFormatterForFieldType(LocalDate.class, new
USLocalDateFormatter());
}
}
3.调用自定义日期格式
1) 首先我们需要在ProfileController添加加下面的代码。
@ModelAttribute("dateFormat")
public String localeFormat(Locale locale) {
return USLocalDateFormatter.getPattern(locale);
}
上面代码的@ModelAttribute的注解,有点像我们之前用过的model.addAttribute(),也就是默认取值给视图层。
2) 在视图层中我们添加下面的代码。
<div class="row">
<div class="input-field col s6">
<input th:field="${profileForm.birthDate}" id="birthDate"
type="text" th:placeholder="${dateFormat}"/>
<label for="birthDate">Birth Date</label>
</div>
</div>
4.总结
这一节我们主要是学习了如何进行日期格式的转换,添加了上面的代码后,如果你是在美国地区,那么将会看到的结果是:
但是这里我们还有问题,那就是客户端输入信息时,我们需要做信息止的校验,那么这个应该实现,在下一节中,我们将会讲解。
源码路径:git@github.com:owenwilliam/masterSpringMVC.git