简体   繁体   English

Spring 使用@RequestBody 时启动获取请求正文

[英]Spring Boot get the request body while using @RequestBody

I'm using Spring Boot @RequestBody annotation to access the request body properties like below我正在使用 Spring Boot @RequestBody 注释来访问请求正文属性,如下所示

@PostMapping
ResponseEntity<UserDto> createUser (@RequestBody UserDto userDto) {
    // some coode
    return null;
}

What I want to do is instead of just accessing the userDto properties.我想要做的不仅仅是访问 userDto 属性。 I want to log the whole request body because someone else is using sending the request and it doesn't match my userDto我想记录整个请求正文,因为其他人正在使用发送请求并且它与我的userDto不匹配

What I tried?我试过什么?

@PostMapping
ResponseEntity<UserDto> createUser (HttpServletRequest request) {
    logger.info("Body: {}", request.getReader().lines().collect(Collectors.toSet()));
    return null;
}

This works just fine but each time I want to log the request body I have to switch between @RequestBody UserDto and HttpServletRequest request这工作得很好,但每次我想记录请求体时,我都必须在@RequestBody UserDtoHttpServletRequest request之间切换

Is there anyway I can keep that jackson @RequestBody annonation and still log request body as it is?无论如何我可以保留 jackson @RequestBody annonation 并且仍然按原样记录请求正文吗?

Information taken from https://www.baeldung.com/spring-http-logging资料取自https://www.baeldung.com/spring-http-logging

You can use Springs CommonsRequestLoggingFilter for this.您可以为此使用 Springs CommonsRequestLoggingFilter。 You can activate this via a Configuration Bean:您可以通过配置 Bean 激活它:

@Configuration
public class RequestLoggingFilterConfig {

    @Bean
    public CommonsRequestLoggingFilter logFilter() {
        CommonsRequestLoggingFilter filter           = new CommonsRequestLoggingFilter();
        filter.setIncludeQueryString(true);
        filter.setIncludePayload(true);
        filter.setMaxPayloadLength(10000);
        filter.setIncludeHeaders(false);
        filter.setAfterMessagePrefix("REQUEST DATA : ");
        return filter;
    }
}

The filter logs on debug, so you need to enable debug logging for the class. For example add this in your logback.xml:过滤器记录调试,因此您需要为 class 启用调试日志记录。例如,在您的 logback.xml 中添加:

<logger name="org.springframework.web.filter.CommonsRequestLoggingFilter">
    <level value="DEBUG" />
</logger>

For reference see https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/filter/CommonsRequestLoggingFilter.html有关参考,请参阅https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/filter/CommonsRequestLoggingFilter.html

You can use ObjectMapper from fasterxml您可以使用来自 fasterxml 的 ObjectMapper

add the following dependencies to the pom.xml:将以下依赖项添加到 pom.xml:

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.3</version>
 </dependency>

Change your createUser method to this:将您的 createUser 方法更改为此:

@PostMapping
ResponseEntity<UserDto> createUser (@RequestBody UserDto userDto)
throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    logger.info("Body: "+  objectMapper.writeValueAsString(userDto));
    return null;
}

Result will be like this in your console:结果将在您的控制台中如下所示:

: Body: {"name":"John","username":"Doe"}

One way to solve this task is to write an Http Filter that logs the message before the Handler method is called.解决此任务的一种方法是编写一个 Http 过滤器,在调用 Handler 方法之前记录消息。

This Baeldung Article demonstrates a filter that logs.这篇Baeldung 文章演示了一个记录日志的过滤器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 弹簧 WebFlux。 如何使用@RequestBody 注释以两种不同格式获取请求正文? - Spring WebFlux. How to get the request body in two different formats using @RequestBody annotation? 在春季使用带有@RequestBody批注的GET请求 - GET request with @RequestBody annotation in Spring 在春季启动时,请求json主体中存在可变键值时处理RequestBody - Handling a RequestBody when there are variable key-value in the request json body in spring boot 使用 Spring 引导请求包装器主体 - Request Wrapper Body using Spring Boot Web服务使用Spring Boot支持RequestBody或RequestParam - Webservice supporting RequestBody or RequestParam using spring boot 如何连接到Spring的@RequestBody参数解析,以使用请求的主体解析我自己的参数 - How can I hook into Spring's @RequestBody argument resolving to resolve my own argument using the body of the request 在使用@Requestbody注释在Spring Boot中进行处理之前,如何在数据库或日志文件中记录JSON或XML请求 - How to log JSON or XML request in a database or log file before processing in Spring boot using @Requestbody annotation Spring Boot解析@RequestBody - Spring boot parsing @RequestBody 空请求正文不会被Spring @RequestBody @Valid注释捕获 - Null request body not getting caught by Spring @RequestBody @Valid annotations 发布请求-春季启动[RequestBody]与Asp.net [FromBody] - Post Request - Spring boot [RequestBody] vs Asp.net [FromBody]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM