3

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?

alcantula
  • 169
  • 1
  • 14

2 Answers2

0

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);
    }
GolamMazid Sajib
  • 8,698
  • 6
  • 21
  • 39
-1

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) {
  • 3
    if `@PathVariable` is too many, it will cause the controller become messy. I want the `@PathVariable` can be wrapped in one object. – alcantula Apr 06 '20 at 14:14
  • with json request {buildingId: x, floorId: y, roomId: z} @getmapping ( "/FunctionName") public Flux getRoomSections (@RequestBody BuildingRequestBean buildingRequestBean) { You can use it this way without adding it to the path. – Berke Şahin Apr 06 '20 at 16:38