【问题标题】:Can spring map POST parameters by a way other than @RequestBody可以通过@RequestBody以外的方式来映射POST参数
【发布时间】:2018-09-15 03:34:34
【问题描述】:

我正在将@RestControllers 与所有请求都是POST 请求的应用程序一起使用...正如我从this post 中了解到的,您不能将单个后置参数映射到单个方法参数,而是需要包装一个对象中的所有参数,然后将此对象用作带有@RequestBody注释的方法参数,因此

@RequestMapping(value="/requestotp",method = RequestMethod.POST) 
    public String requestOTP( @RequestParam(value="idNumber") String idNumber , @RequestParam(value="applicationId") String applicationId) {
        return customerService.requestOTP(idNumber, applicationId);

不适用于 POST 正文 {"idNumber":"345","applicationId":"64536"} 的请求

我的问题是我有 A LOTPOST 请求,每个只有一两个参数,创建所有这些对象只是为了接收里面的请求会很乏味......那么还有其他类似于get请求参数(URL参数)的处理方式吗?

【问题讨论】:

  • 您的请求正文为 json 格式,您正在接收表单类型的数据。请将请求正文更改为非 json 类型的表单类型
  • 我正在尝试使用高级休息客户端,我看不到表单类型...你的意思是 multipart/form-data 吗?
  • 不,您应该以 form-data 格式发送数据
  • 您可以将所有参数绑定在单个类中,并将其作为@RequestBody 接受,并根据您的要求使用getter setter获取参数。

标签: spring spring-mvc spring-restcontroller


【解决方案1】:

是的,有两种方法-

首先 - 你正在做的只是你需要做的就是将这些参数附加到 url,不需要在正文中给出它们。 url 就像 - baseurl+/requestotp?idNumber=123&applicationId=123

@RequestMapping(value="/requestotp",method = RequestMethod.POST) 
    public String requestOTP( @RequestParam(value="idNumber") String idNumber , @RequestParam(value="applicationId") String applicationId) {
        return customerService.requestOTP(idNumber, applicationId);

第二个——你可以按如下方式使用地图

 @RequestMapping(value="/requestotp",method = RequestMethod.POST) 
    public String requestOTP( @RequestBody Map<String,Object> body) {
        return customerService.requestOTP(body.get("idNumber").toString(), body.get("applicationId").toString());

【讨论】:

  • 好...但是如果我想对参数@Valid 应用自动验证怎么办...我想我不能使用地图,对吧?
  • 是的,如果您将使用地图,那么您必须手动进行验证
  • 如果我的参数之一是字符串数组怎么办?我想我可以用管道分隔然后在后端拆分,但是有本地解决方案吗?
【解决方案2】:

我已更改您的代码,请检查它

DTO 类

public class DTO1 {


private String idNumber;
private String applicationId;

public String getIdNumber() {
    return idNumber;
}

public void setIdNumber(String idNumber) {
    this.idNumber = idNumber;
}

public String getApplicationId() {
    return applicationId;
}

public void setApplicationId(String applicationId) {
    this.applicationId = applicationId;
}

}

休息控制器方法

@RequestMapping(value="/requestotp",method = RequestMethod.POST) 
public String requestOTP( @RequestBody DTO1 dto){
    System.out.println(dto.getApplicationId()+"  (------)  "+dto.getIdNumber());
    return "";
}

请求类型——应用程序/json {"idNumber":"345","applicationId":"64536"}

@RequestMapping(value="/requestotp",method = RequestMethod.POST) 
public String requestOTP( @RequestBody String dto){
    System.out.println(dto);
    return "";
}

【讨论】:

  • 实际上我的问题是如何避免这种方法:) .... 因为我需要为每个请求创建一个 DTO
  • 是的,您必须将请求类型更改为表单数据
  • 你可以在这里发布答案,让每个人都受益
  • 我也受到前端(Angular)发送json的限制
  • 请检查我的更新答案,我认为第二个 ANS 将解决您的问题。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-29
  • 2015-03-28
  • 1970-01-01
  • 1970-01-01
  • 2022-11-20
  • 2021-11-16
相关资源
最近更新 更多