从Spring Boot控制器方法读取HttpServletRequest对象

时间:2019-09-12 00:56:23

标签: java spring rest spring-boot spring-mvc

下面是我的控制器方法定义

@Autowired
private HttpServletRequest request;

@PostMapping(path = "/abc")
public String createAbc(@RequestBody HttpServletRequest request)
        throws IOException {

    logger.info("Request body: "+request.getInputStream());

    return "abc";

}

我要做的就是打印内容以请求正文。 但是当我发出POST请求时,看到以下错误:

  

类型定义错误:[简单类型,类   javax.servlet.http.HttpServletRequest];嵌套异常为   com.fasterxml.jackson.databind.exc.InvalidDefinitionException:无法   构造javax.servlet.http.HttpServletRequest的实例(否   像默认构造一样,创建者也存在):抽象类型要么需要   映射到具体类型,具有自定义反序列化器或包含   其他类型信息\ n,位于[来源:(PushbackInputStream);线:   1,栏:2]“,

我正在使用Spring boot 2.x版本。知道我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:3)

首先,删除@Autowired字段。这是错误的,您无论如何都不会使用它。

现在您有两种选择:

  1. 让Spring通过使用@RequestBody批注为您处理请求正文:

    @PostMapping(path = "/abc")
    public String createAbc(@RequestBody String requestBody) throws IOException {
        logger.info("Request body: " + requestBody);
        return "abc";
    }
    
  2. 自己处理,即不要使用@RequestBody批注:

    @PostMapping(path = "/abc")
    public String createAbc(HttpServletRequest request) throws IOException {
        StringBuilder builder = new StringBuilder();
        try (BufferedReader in = request.getReader()) {
            char[] buf = new char[4096];
            for (int len; (len = in.read(buf)) > 0; )
                builder.append(buf, 0, len);
        }
        String requestBody = builder.toString();
        logger.info("Request body: " + requestBody);
        return "abc";
    }
    

不知道为什么要使用选项2,但是可以。