注意:只能接受@RequestBody
类型的input参数。
Controller
1 2 3 4 5 6 7 8 9 10 11 12 13
| package com.example.demo.demos.web;
import org.springframework.web.bind.annotation.*;
@RestController public class BasicController {
@RequestMapping("/hello") @ResponseBody public String hello(@RequestBody String name) { return "Hello " + name; } }
|
Advice
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| package com.example.demo.demos.web;
import lombok.extern.slf4j.Slf4j; import org.springframework.core.MethodParameter; import org.springframework.http.HttpInputMessage; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import java.io.IOException; import java.lang.reflect.Type; import java.util.Arrays;
@Slf4j @RestControllerAdvice public class RequestBodyAdviceImpl implements RequestBodyAdvice { @Override public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) { return true; }
@Override public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException { RequestMapping requestMapping = parameter.getMethodAnnotation(RequestMapping.class); log.info("url: " + Arrays.toString(requestMapping.value())); log.info("method: " + parameter.getExecutable()); return inputMessage; }
@Override public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) { log.info("param: " + body); return body; }
@Override public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) { log.info("body: body is Empty"); return body; } }
|
执行结果