【问题标题】:Spring @ModelAttribute Model field mappingSpring @ModelAttribute 模型字段映射
【发布时间】:2020-03-16 15:41:23
【问题描述】:

我正在重写在内部框架中编写的旧 REST 服务以使用 Spring。我有一个带有 POST 方法的控制器,该方法将参数作为 POST 或 x-www-form-urlencoded 正文。根据多个 StackOverflow 答案,我使用了 @ModelAttribute 注释并创建了一个模型。

我的问题是旧的 REST API 在蛇形情况下使用属性名称 - 比如some_property。我希望我的 Java 代码遵循 Java 命名约定,因此在我的模型中,该字段称为 someProperty。我尝试像在 DTO 对象中一样使用 @JsonProperty 注释,但这次没有用。如果模型中的字段名为some_property,我只能设法使代码工作。这是我的示例代码:

import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/my/api/root")
public class SomethingController {

    @PostMapping("/my/api/suffix")
    public Mono<Object> getSomething(
            @RequestParam(name = "some_property", required = false) String someProperty,
            @ModelAttribute("some_property") Model somePropertyModel) {
        // calling my service here
    }

    public class Model {
        @JsonProperty("some_property")
        private String someProperty;

        private String some_property;
        // Getters and setters here
    }
}

我正在寻找注释或任何其他优雅的方式来保持代码中的 Java 命名风格,但使用 REST API 中的旧属性名称。

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    @JsonProperty 注解只能使用 JSON 格式,但您使用的是 x-www-form-urlencoded

    如果不能更改 POST 类型,则必须编写自己的 Jackson ObjectMapper:

    @JsonProperty not working for Content-Type : application/x-www-form-urlencoded

    【讨论】:

    • 我接受这个答案,因为它引导我回答了我的问题 - 不,没有优雅的方法可以实现我想要的。我不会出于审美目的编写大量代码。到目前为止,还没有合适的注解(参见 Spring Jira 问题:jira.spring.io/browse/SPR-13433)。您链接的问题的答案之一(不是已接受的答案)让我们看到一篇文章,该文章显示了解决此问题的几种替代方法。这是链接:afitnerd.com/2017/05/24/…
    • @ShaMan-H_Fel 好的,感谢您的反馈,TIL。
    【解决方案2】:

    我也遇到过你类似的情况, 请将@ModelAttribute("some_property") 替换为@RequestBody

    希望能帮到你!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      • 2018-07-29
      • 2015-09-05
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 2012-09-02
      相关资源
      最近更新 更多