Spring Bind @PathVariable to JavaBean

Viewed 727

I try to bind an object in Spring controller so it can be used as @PathVariable. I want to do so, since there are some @PathVariable that I want to pass. I have tried the solution from Bind Path variables to a custom model object in spring and also Is it possible to bind path variable and request param into a single object?. But both are not working.

I have created something like this in my controller.

@RestController
@RequestMapping("/buildings")
@RequiredArgsConstructor
public class BuildingController {

    private final BuildingService buildingService;

    @GetMapping("/{buildingId}/floors/{floorId}/rooms/{roomId}/sections")
    public Flux<SectionDTO> getRoomSections(BuildingRequestBean request) {
        return this.buildingService.getRoomSections(request);
    }
}

and BuildingRequestBean.java like this

@Getter
@Setter
public class BuildingRequestBean {

  private String buildingId;

  private String floorId;

  private String roomId;
}

When I check BuildingRequestBean, the attributes is null when I call it with GET localhost:8080/buildings/a/floors/b/rooms/c/sections. However, it will not null if I call it as @RequestParam, something like this GET localhost:8080/buildings/{buildingId}/floors/{floorId}/rooms/{roomId}/sections?buildingId=a&floorId=b&roomId=c

How to fix it so it will behave like @PathVariable rather than behave like @RequestParam?

2 Answers

U can get it by using @ModelAttribute

Try with this:

@GetMapping("/{buildingId}/floors/{floorId}/rooms/{roomId}/sections")
    public Flux<SectionDTO> getRoomSections(@ModelAttribute BuildingRequestBean request) {
        return this.buildingService.getRoomSections(request);
    }

PathVariable must be added to the function parameter

Try this :

@GetMapping("/{buildingId}/floors/{floorId}/rooms/{roomId}/sections")
public Flux<SectionDTO> getRoomSections(@PathVariable String buildingId,@PathVariable String floorId ,@PathVariable String roomId) {
Related