如何将@RequestParam与DTO一起使用

问题描述 投票:0回答:3

我必须使用 DTO 来创建 GET 方法。 但是当我这样编码时↓,就会出现错误。 org.springframework.web.bind.MissingServletRequestParameterException:方法参数类型 SampleDTO 所需的请求参数“param”不存在

检查该错误后,我发现我需要添加选项@RequestParam(required=false)。 然后,我重新启动了tomcat。 虽然没有更多错误,但我的参数为空(我实际上发送了sample_name)。

我尝试同时使用无注释和@ModelAttribute。 两者都出现同样的错误↓ 引起:java.lang.NoSuchMethodError:org.springframework.beans.BeanUtils.getResolvableConstructor(Ljava/lang/Class;)Ljava/lang/reflect/Constructor;

我该怎么办?请给我建议。 我不知道处理 DTO 的最佳方法。 因为我实际上通常使用 HashMap 进行编码。

这是我的示例代码。

//控制器示例
要点:insertSample方法效果很好。

@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 示例

@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;
    }

}
spring spring-boot dto
3个回答
2
投票

为了将请求参数绑定到对象,您需要在 DTO 类中拥有标准的 getter/setter。将

@Setter
添加到您的方法中,然后您甚至无需任何注释即可绑定。

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

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

尝试这样,你应该指定变量


0
投票
@GetMapping    
public Result getSampleList(SampleDTO param) throws Exception {}

删除 @RequestParam 注释并添加设置器对我有用。 也可以在 DTO 内设置默认值,例如:

public class SampleDTO {
    private String sampleName = "myDefaultValue";

    //setters
}

如果请求包含 dto 中不存在的参数,则其将被忽略。

如果请求中不存在 dto 成员变量,并且没有默认值,则其为 null。

有没有办法将参数标记为 dto 内所需的?

© www.soinside.com 2019 - 2024. All rights reserved.