解決:springmvc中接收date數據問題


這里提供三種解決方案。 

一.局部轉換 :只是對當前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 接受前台的時間格式 傳到后台的格式

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM