Spring MVC @RestController & # 8594; PUTting results in "400 Bad Request" no matter what I do
I have a Spring RestController that works great when I get GET
data from it, but when I try PUT
the same data I get 400 Bad Request
.
Here is the simplest version of my controller that should work (I didn't use the method 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;
}
}
This 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;
}
}
I pretty much copied this code from another branch and it works there!
I can't figure it out!
EDIT
Here's the GET
-Method:
@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;
}
And the result it produces (for an LED strip of length 1):
{
"pixels": [
{
"red": 0,
"green": 16,
"blue": 0
}
],
"_links": {
"self": {
"href": "http://localhost:8080/configuration/ledstrips/devled/display"
}
}
}
When I post this, whether with _links
or without a segment , I get an error 400
.
source to share
Like PUT
, you have defined produces
, but not consumes
. Maybe the endpoint doesn't know what format the body expects, so it rejects it. Attempt: Strike>
Looking at the source you provided, I can see that the class Color
has a constructor that requires arguments. The default ObjectMapper
provided by the Jackson Libraries will not be able to revoke the JSON token because of this constructor. Try adding a default constructor to the class Color
next to the current one:
public Color(int red, int green, int blue) {
this.red = setColorLimits(red);
this.green = setColorLimits(green);
this.blue = setColorLimits(blue);
}
public Color() {}
source to share