Home > Blockchain >  How to use @RequestParam with DTO
How to use @RequestParam with DTO

Time:08-02

I have to make GET method with a DTO. But when I code like this↓, an error occurs. org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'param' for method parameter type SampleDTO is not present

After checking that error, I figured out I need add option @RequestParam(required=false). Then, I restarted tomcat. Although there was no more error, my param was null(I actually sent sample_name). enter image description here

And I tried to use both of no annotation and @ModelAttribute. Both of them occurs same error↓ Caused by: java.lang.NoSuchMethodError: org.springframework.beans.BeanUtils.getResolvableConstructor(Ljava/lang/Class;)Ljava/lang/reflect/Constructor;

What should I do? plz give me advice. I don't know best way handling DTO. Because I usually coded using HashMap actually.

Here is my example code.

//Controller sample
point: insertSample method works well.

@RestController
@RequestMapping("/sample")
public class SampleController {

    @Autowired
    private SampleService sampleService;

    @GetMapping
    public Result getSampleList(@RequestParam SampleDTO param) throws Exception {
        // (@RequestParam(required=false) SampleDTO param)
        // (@ModelAttribute SampleDTO param)
        // (SampleDTO param)
        return sampleService.getFolderList(param);
    }

    @PostMapping
    public Result insertSample(@RequestBody SampleDTO param) throws Exception {
        return sampleService.insertFolder(param);
    }
}

// DTO sample

@Getter // I didn't attach @Setter because of @Builder.
@NoArgsConstructor
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
@Alias("SampleDTO")
public class SampleDTO {

    @NotNull
    private Long sampleNo;

    @NotBlank
    private String sampleName;

    private String sampleDesc;

    @Builder
    public SampleDTO(Long sampleNo, String sampleName, String sampleDesc) {
        this.sampleNo = sampleNo;
        this.sampleName = sampleName;
        this.sampleDesc = sampleDesc;
    }

}

CodePudding user response:

In order to bind request parameters to object you need to have standard getters/setters in your DTO class. Add @Setter to your method, then you can bind without even any annotation.

    @GetMapping
    public Result getSampleList(SampleDTO param) throws Exception {
        return sampleService.getFolderList(param);
    }

CodePudding user response:

@GetMapping
public Result getSampleList(@RequestParam("param") SampleDTO param) throws Exception {
    // (@RequestParam(required=false) SampleDTO param)
    // (@ModelAttribute SampleDTO param)
    // (SampleDTO param)
       return sampleService.getFolderList(param);
    }
}

Try like this, You should have to designate variable

  • Related