【问题标题】:Having alias param names to accept Url Encoded Form data values具有别名参数名称以接受 Url Encoded Form 数据值
【发布时间】:2020-03-11 12:02:40
【问题描述】:

在我的 Spring Web 应用程序中,我有一个 API 可以接受 application/x-www-form-urlencoded 内容类型的请求。

@RequestMapping(value = "/do-it", method = {RequestMethod.POST})
public String test(@ModelAttribute("request")RequestDTO request,HttpServletRequest
            httpServletRequest, Map<String, Object> model, RedirectAttributes redirectAttributes){

            .....
}

我的 RequestDTO 中有以下字段。

public class RequestDTO {

    private String paramOne;

    private String paramTwo;

    // standard getters and setters

}

此实现工作正常,所有请求参数都按预期映射到请求 dto。但是,现在我有这个要求来接受具有以下模式的字段的请求。

param_one,param_two

我知道,在我的请求 dto 中的字段上使用 @JsonProperty 注释在我的情况下不起作用,因为请求不是 application/json 的类型。

我发现解决该问题的唯一方法是创建新的 setter,例如以下(在我看来,在命名约定方面看起来很丑)。

public void setParam_one(String param_one) {
        this.paramOne = param_one;
}

有人可以帮我找到更好的方法来完成这项工作吗?我无法更改原始请求 dto 中的参数名称。

谢谢你..!

【问题讨论】:

  • stackoverflow.com/questions/8986593/… 回答你的问题了吗?
  • 嗯,它有帮助,不是直接的。我能够从那里找到一个关键字,即“参数解析器”。然后用谷歌搜索它并找到了完成我的工作的方法。我会在这里添加它作为答案

标签: java spring spring-boot httprequest x-www-form-urlencoded


【解决方案1】:

我能够完成这项工作。感谢@neetash 指导我。

我需要的只是一个自定义 HandlerMethodArgumentResolver 来将发布请求正文数据映射到我想要获取的对象。

我按照以下链接教程来实现它。它包含创建 HandlerMethodArgumentResolver 需要知道的每一件事。

https://www.petrikainulainen.net/programming/spring-framework/spring-from-the-trenches-creating-a-custom-handlermethodargumentresolver/

【讨论】:

    猜你喜欢
    • 2014-11-22
    • 2021-01-04
    • 2022-07-06
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多