400錯誤與“springmvc實體類接收帶時間字符串的json請求”

springmvc使用實體類接收參數

這個問題,需要在springmvc的配置文件中,添加上AnnotationMethodHandlerAdapter這個類,具體配置參考博客:
參考1
參考2
結合兩個博客,我的配置


<!-- 用於將對象轉換爲 JSON ,支持前端表單請求和json請求,接收請求時自動轉成pojo對象 -->
    <bean id="stringConverter"
          class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=utf-8</value>
                <value>application/json;charset=utf-8</value>
            </list>
        </property>
    </bean>

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringConverter"/>
                <ref bean="jsonConverter"/>
            </list>
        </property>
    </bean>

json請求中帶時間字符串,怎麼處理

參考鏈接,這個總結的很全面,贊!
我採用了其中比較方便的一種方式

@Table(name = "device_status")
public class DeviceStatus {

    /**
     * 主鍵
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "project_id")
    private String projectId;
    @Column(name = "device_id")
    private String deviceId;
    private Byte status;
    @Column(name = "event_time")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
//    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8")
    private Date eventTime;
//此處兩種格式註解效果一樣

400錯誤表現說明

  • 一般來說400錯誤是bad request 錯誤,通常是請求參數和接受參數不一致導致的。
  • 正常的json請求中,如果有時間,那也只能是時間字符串(String類型)
  • 實體類中定義的時間字段的類型是Date類型:private Date eventTime;
//請求參數,請求頭中:Content-Type=“application/json”
//請求body如下
{
    "projectId": "SZ0112",
    "deviceId": "c55d9e190",
    "status": 1,
    "eventTime": "2019-10-22 13:31:23"
}

基於以上3個條件, springmvc 的controller中,使用@requestBody接收請求來的json時無法把String類型的 “eventTime”: "2019-10-22 13:31:23"屬性字段匹配到實體類的時間字段private Date eventTime;

於是報錯400 bad request

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章