【问题标题】:Post request not bind data with POJO class in spring mvc Rest api.发布请求未在 spring mvc Rest api 中与 POJO 类绑定数据。
【发布时间】:2016-07-22 07:27:19
【问题描述】:

我对rest api概念很陌生。我正在尝试实现一个可以接收 post 方法的简单方法。问题是请求命中方法但没有将数据与 POJO 类绑定。 这是我的代码。

@RestController
public class HomeController {

private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

@ResponseBody
@RequestMapping(value = "/", method = RequestMethod.POST)
public CompileRequest home(@ModelAttribute CompileRequest compileRequest) {
    logger.info("user name : {}", compileRequest.getUserName()); // null
    logger.info("input file path : {}", compileRequest.getInputFilePath()); //null
    return compileRequest;
}
}

我没有使用@RequestBody,因为它给了我 415 http 错误。 这是我的 POJO 课程。

@Data // use lombok for getter and setter. 
public class CompileRequest {
   private String userName;
   private String inputFilePath;
}

userNameinputFilePath 字段仍保留为 null。我不明白为什么数据绑定不起作用。我该如何解决这个问题?

谢谢。

【问题讨论】:

  • 当你使用 @RequestBody 时你得到的堆栈跟踪是什么?
  • 添加这3个依赖然后使用@RequestBody看看是否有效gist.github.com/sazzadislam-dsi/…
  • @LynAs 依赖项已添加到 pom.xml 中。它最终不会生成任何堆栈跟踪,但在响应中它说The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
  • 你能在结构标签中看到getter/setter吗??
  • @LynAs 是的。我认为龙目岛工作正常。我在代码的其他部分调用了 getter/setter 方法。

标签: rest spring-mvc http-post


【解决方案1】:

如下使用返回。由于您想要休息响应,它还为您提供了发送正确状态代码的选项

public ResponseEntity<?> home(@RequestBody CompileRequest compileRequest) {

   return return ResponseEntity.ok(compileRequest);
}

CompileRequest 类的顶部添加以下内容

@NoArgsConstructor(access = AccessLevel.PUBLIC)
@AllArgsConstructor(access = AccessLevel.PUBLIC)

如果你还没有,也可以添加以下依赖

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson}</version>
        </dependency>

最终以 Json 形式发送数据

{

   "userName" : "name",
   "inputFilePath": "path"

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2014-09-05
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2015-03-28
    相关资源
    最近更新 更多