POST JSON fails with 415 Unsupported media type, Spring 3 mvc

后端 未结 14 1566
执念已碎
执念已碎 2020-11-22 09:46

I am trying to send a POST request to a servlet. Request is sent via jQuery in this way:

var productCategory = new Object();
productCategory.idProductCategor         


        
14条回答
  •  忘了有多久
    2020-11-22 10:15

    I believe I ran exactly into the same issue. After countless hours of fighting with the JSON, the JavaScript and the Server, I found the culprit: In my case I had a Date object in the DTO, this Date object was converted to a String so we could show it in the view with the format: HH:mm.

    When JSON information was being sent back, this Date String object had to be converted back into a full Date Object, therefore we also need a method to set it in the DTO. The big BUT is you cannot have 2 methods with the same name (Overload) in the DTO even if they have different type of parameter (String vs Date) because this will give you also the 415 Unsupported Media type error.

    This was my controller method

      @RequestMapping(value = "/alarmdownload/update", produces = "application/json", method = RequestMethod.POST)
      public @ResponseBody
      StatusResponse update(@RequestBody AlarmDownloadDTO[] rowList) {
        System.out.println("hola");
        return new StatusResponse();
      }
    

    This was my DTO example (id get/set and preAlarm get Methods are not included for code shortness):

    @JsonIgnoreProperties(ignoreUnknown = true)
    public class AlarmDownloadDTO implements Serializable {
    
      private static final SimpleDateFormat formatHHmm = new SimpleDateFormat("HH:mm");
    
      private String id;
      private Date preAlarm;
    
      public void setPreAlarm(Date date) { 
        this.preAlarm == date;
      }
      public void setPreAlarm(String date) {    
        try {
          this.preAlarm = formatHHmm.parse(date);
        } catch (ParseException e) {
          this.preAlarm = null;
        } catch (NullPointerException e){
          this.preAlarm = null;
        }
      }
    }
    

    To make everything work you need to remove the method with Date type parameter. This error is very frustrating. Hope this can save someone hours of debugging.

提交回复
热议问题