這里提供三種解決方案。
一.局部轉換 :只是對當前Controller類有效
springMVC.xml中添加:
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="stringHttpMessageConverter" /> </list> </property> </bean> <!-- String類型解析器,允許直接返回String類型的消息 --> <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter" /> <!-- 日期轉換 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="webBindingInitializer"> <bean class="com.rw.tools.ConvertDate"/> </property> </bean>
Controller 類文件中添加:
@Controller @RequestMapping("/image") public class ImageController { @Autowired private ImageService imageService; @org.springframework.web.bind.annotation.InitBinder public void InitBinder(WebDataBinder binder){ DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); CustomDateEditor dateEditor = new CustomDateEditor(df, true); binder.registerCustomEditor(Date.class,dateEditor); }
二.全局轉換
1.創建convertDate類實現WebBindingInitializer接口
public class convertDate implements WebBindingInitializer{ @Override public void initBinder(WebDataBinder binder, WebRequest request) { // TODO Auto-generated method stub //轉換日期 DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } }
2.在Spring-MVC.xml中配置日期轉換
<!-- 日期轉換 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="com.wx.web.convertDate"/>
</property>
</bean>
三.實體類屬性方法配置
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")//接受前台的時間格式 傳到后台的格式 @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")//作用:后台的時間 格式化 發送到前台 private Date date;
@JsonFormat 默認是標准時區的時間, 北京時間 東八區 timezone=”GMT+8”
作用:后台的時間 格式化 發送到前台
@DateTimeFormat 接受前台的時間格式 傳到后台的格式
