2

我知道这个问题已经被问了无数次,但我仍然找不到我的问题的解决方案,这基本上归结为来自 PUT 请求的 JSON 反序列化。

我已经添加了 HiddenHttpMethodFilter 作为过滤器。

org.codehaus.jackson.jackson-mapper-lgpl 在类路径中。

这是客户端部分:

$.ajax({
    url: '/occurrence',
    type: 'PUT',
    contentType: 'application/json',
    data: JSON.stringify({id:id,startDate:startDate, endDate:endDate, frequencyType:frequency})
 })

这是控制器部分:

@Controller
@RequestMapping("/occurrence")
public class OccurrenceController {

    private static final String COMMAND = "eventCommand";

    @Autowired
    private PersistenceCapableOccurrence occurrenceDao;

    @Autowired
    private PersistenceCapableFrequencyType frequencyTypeDao;

    @InitBinder(COMMAND)
    public void customizeConversions(final WebDataBinder binder) {
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        df.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, true));

        EntityConverter<FrequencyType> frequencyTypeEntityConverter = new EntityConverter<FrequencyType>(frequencyTypeDao, FrequencyType.class, "findByValue", String.class);
        ((GenericConversionService) binder.getConversionService()).addConverter(frequencyTypeEntityConverter);
    }

    @RequestMapping(method = PUT, consumes = "application/json")
    @ResponseBody
    public Long saveOccurrence(@RequestBody Occurrence occurrence) {
        return occurrenceDao.saveOrUpdate(occurrence);
    }
}

这是我的两个域类(Occurrence 和 FrequencyType):

public class Occurrence {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", nullable = false)
    private long id;
    @NotNull
    @Column(name = "start_date")
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    private DateTime startDate;
    @Column(name="end_date")
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    private DateTime endDate;
    @ManyToOne
    @JoinColumn(name = "frequency_type", nullable = false)
    private FrequencyType frequencyType;

     /* C-tor (1 with [start,end,freq], another with [start,freq]), getters (no setters) */
}

@Entity
@Table(name = "frequency_types")
public class FrequencyType {

    public enum FrequencyTypeValues {
        ONCE, DAILY, WEEKLY, MONTHLY, YEARLY;
    }

    private String value;

    public FrequencyType() {}
    public FrequencyType(FrequencyTypeValues value) {
        this.value = value.name();
    }

    @Id
    @Column(name = "value")
    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        //validates value against the enumerated/allowed values (ie throws exceptions if invalid value)
        FrequencyTypeValues.valueOf(value.toUpperCase());
        this.value = value;
    }
}

最后我得到的只是 400 响应。例子 :

PUT Request
{"id":"","startDate":"20/10/2012 17:32","endDate":"","frequencyType":"YEARLY"}

Response
"NetworkError: 400 Bad Request - http://localhost:9999/occurrence"

在此先感谢您的帮助 !罗尔夫

4

0 回答 0