Spring MVC @RestController -> 无论我做什么,PUTting 都会导致“400 Bad Request”

Spring MVC @RestController -> PUTting results in "400 Bad Request" no matter what I do

我有一个 Spring RestController,当我 GET 来自它的数据时它工作得很好,但是当我尝试 PUT 非常相同的数据时 , 我得到一个 400 Bad Request.

这是我的控制器的最简单版本,应该 仍然有效(我省略了 GET 方法):

@RestController
@RequestMapping("/configuration/ledstrips/{name}/display")
public class DisplayController {

    @ResponseBody
    @RequestMapping(method = RequestMethod.PUT, produces = { "application/hal+json" })
    public DisplayResource setDisplay(@PathVariable String name, @RequestBody DisplayResource display) {

        return display;
    }
}

这是DisplayResource:

public class DisplayResource extends ResourceSupport {

    private List<Color> pixels;

    public List<Color> getPixels() {

        return pixels;
    }


    public void setPixels(List<Color> pixels) {

        this.pixels = pixels;
    }
}

我几乎是从另一个分支复制这段代码,并且它有效!

想不通!

编辑

这是 GET-方法:

@ResponseBody
@RequestMapping(method = RequestMethod.GET, produces = { "application/hal+json" })
public DisplayResource getDisplay(@PathVariable String name) {

    LEDStripDTO ledStripDTO;

    try {
        ledStripDTO = ledStripDTOService.getDTO(name);
    } catch (IOException | NullPointerException exception) {
        throw new LoadFailedException("Error loading LED strip:", exception);
    }

    Link self = linkTo(methodOn(DisplayController.class).getDisplay(name)).withSelfRel();

    DisplayResource displayResource = new DisplayResource();

    displayResource.add(self);

    try {
        displayResource.setPixels(ledStripService.getPixels(ledStripDTO));
    } catch (IOException | TimeoutException | AlreadyConnectedException | NotConnectedException exception) {
        throw new LoadFailedException("Error getting Information from LED strip:", exception);
    }

    return displayResource;
}

它产生的结果(对于长度为 1 的 LED 灯条):

{
  "pixels": [
    {
      "red": 0,
      "green": 16,
      "blue": 0
    }
  ],
  "_links": {
    "self": {
      "href": "http://localhost:8080/configuration/ledstrips/devled/display"
    }
  }
}

当我发送此邮件时,无论有无 _links 段,我都会收到 400 错误。

因为它是 PUT,所以您定义了 produces 而不是 consumes。可能是端点不知道期望正文采用什么格式,这就是它拒绝它的原因。尝试:

查看了您提供的源代码后,我发现 Color class 有一个需要参数的构造函数。由于此构造函数,Jackson 库提供的默认 ObjectMapper 将无法解组 JSON 字符串。尝试将默认构造函数添加到 Color class 以及当前构造函数:

public Color(int red, int green, int blue) {

    this.red = setColorLimits(red);
    this.green = setColorLimits(green);
    this.blue = setColorLimits(blue);
}

public Color() {}