java - 将 post 参数映射到请求中的 DTO

标签 java spring spring-mvc spring-boot java-8

在我的 Spring 启动应用程序中,我发送带有以下(例如)参数的 POST 数据:

data: {
        'title': 'title',
        'tags': [ 'one', 'two' ],
        'latitude': 20,
        'longitude': 20,
        'files': [ ], // this comes from a file input and shall be handled as multipart file
    }

在我的@Controller中我有:

@RequestMapping(
        value = "/new/upload", method = RequestMethod.POST,
        produces = BaseController.MIME_JSON, consumes = BaseController.MIME_JSON
)
public @ResponseBody HttpResponse performSpotUpload(final SpotDTO spot) {
// ...
}

其中 SpotDTO 是一个非 POJO 类,具有所有 gettersetter

public class SpotDTO implements DataTransferObject {

    @JsonProperty("title")
    private String title;

    @JsonProperty("tags")
    private String[] tags;

    @JsonProperty("latitude")
    private double latitude;

    @JsonProperty("longitude")
    private double longitude;

    @JsonProperty("files")
    private MultipartFile[] multipartFiles;

    // all getters and setters
}

不幸的是,当我收到请求时,所有字段都是 null。 Spring 无法将参数映射到我的 DTO 对象。

我想我缺少一些配置,但我不知道是哪一个。


其他类似的问题只需在 DTO 类上设置字段访问器即可解决。这对我不起作用。

我还注意到,如果我在方法中指定每个参数:

@RequestParam("title") final String title,

请求甚至没有到达该方法。我可以在 LoggingInterceptor preHandle 方法中看到传入请求,但在 postHandle 中什么也看不到。返回一个 404 响应。

最佳答案

我想你只是错过了 @RequestBody参数注释:

@RequestMapping(
        value = "/new/upload", method = RequestMethod.POST,
        produces = BaseController.MIME_JSON, consumes = BaseController.MIME_JSON
)
public @ResponseBody HttpResponse performSpotUpload(@RequestBody final SpotDTO spot) {
    // ...
}

关于java - 将 post 参数映射到请求中的 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48936069/

相关文章:

java - redisson java 客户端能否检测到集群拓扑中失败的主副本对的重启?

java - 2019年客户端-服务器之间的高效数据库同步

Spring Boot Actutor Web 指标 - 禁用(或分组)http_server_requests_seconds_sum

java - 如何通过 JSON 发送带有多个参数的 put http 请求

java - Netbeans "illegal start of type"错误

JavaEE面向对象网络

java - Spring:如何动态设置最大并发 session 数

spring-mvc - 在 spring mvc 中过滤特定的 HTTP 动词

java - 自动登录后如何将 cookie 导出到 Selenium 中的文件

spring - request.getServletPath() 从 Spring MVC 返回 null