场景
controller
@GetMapping("/userInfo")
public string userInfo( ModelMap mmap){
UserInfo user = new UserInfo();
user.setRegDate(new Date());
user.setName("测试");
mmap.put("userInfo",user);
return "userInfo";
}
userInfo.html
<div id="app">
用户名称:{{userInfo.name}}<br/>
注册日期:{{userInfo.regDate}}
</div>
<script th:inline="javascript">
var userInfo= [[${userInfo}]];
var app = new Vue({
el:"#app",
data(){
return {
userInfo:userInfo
}
}
});
</script>
@Configuration
public class ThymeleafConfig {
@PostConstruct
public void init() {
SpringTemplateEngine springTemplateEngine = SpringUtils.getBean(SpringTemplateEngine.class);
SpringStandardDialect springStandardDialect = CollectionUtils.findValueOfType(springTemplateEngine.getDialects(), SpringStandardDialect.class);
IStandardJavaScriptSerializer standardJavaScriptSerializer = springStandardDialect.getJavaScriptSerializer();
// 通过反射获取 ObjectMapper
Field field = ReflectionUtils.findField(standardJavaScriptSerializer.getClass(), "delegate");
ReflectionUtils.makeAccessible(field);
Object delegate = ReflectionUtils.getField(field, standardJavaScriptSerializer);
Field field2 = ReflectionUtils.findField(delegate.getClass(), "mapper");
ReflectionUtils.makeAccessible(field2);
ObjectMapper objectMapper = (ObjectMapper) ReflectionUtils.getField(field2, delegate);
// 设置新的格式化日期规则
objectMapper.setDateFormat(new JacksonThymeleafISO8601DateFormat2());
}
private static final class JacksonThymeleafISO8601DateFormat2 extends DateFormat {
private static final long serialVersionUID = 1354081220093875129L;
private SimpleDateFormat dateFormat;
JacksonThymeleafISO8601DateFormat2() {
super();
// 主要修改地方
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
setCalendar(this.dateFormat.getCalendar());
setNumberFormat(this.dateFormat.getNumberFormat());
}
@Override
public StringBuffer format(final Date date, final StringBuffer toAppendTo, final FieldPosition fieldPosition) {
final StringBuffer formatted = this.dateFormat.format(date, toAppendTo, fieldPosition);
return formatted;
}
@Override
public Date parse(final String source, final ParsePosition pos) {
throw new UnsupportedOperationException(
"JacksonThymeleafISO8601DateFormat should never be asked for a 'parse' operation");
}
@Override
public Object clone() {
JacksonThymeleafISO8601DateFormat2 other = (JacksonThymeleafISO8601DateFormat2) super.clone();
other.dateFormat = (SimpleDateFormat) dateFormat.clone();
return other;
}
}
}