我想获取发布到RestController的原始内容。我需要它对原始输入进行一些处理。
如何在不干扰过滤链的情况下获取原始内容?
答案 0 :(得分:7)
以下是controllerAdvice的示例,您可以像在控制器中一样访问RequestBody和RequestHeader。 Model属性方法基本上是添加在所有页面或控制器流中使用的模型属性。它在控制器方法启动之前被调用。它提供了更清晰的方式来访问RESTful功能而不是复杂的方式。
@ControllerAdvice(annotations = RestController.class)
public class ControllerAdvisor {
@ModelAttribute
public void addAttributes(HttpServletRequest request, HttpServletResponse response,Model model, @RequestBody String requestString, @RequestHeader(value = "User-Agent") String userAgent) {
// do whatever you want to do on the request body and header.
// with request object you can get the request method and request path etc.
System.out.println("requestString" + requestString);
System.out.println("userAgent" + userAgent);
model.addAttribute("attr1", "value1");
model.addAttribute("attr2", "value2");
}
}
答案 1 :(得分:1)
我使用@ModelAttribute方法从@RequestBody设置值。
@ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler
{
public CustomRestExceptionHandler() {
super();
}
private Object request;
@ModelAttribute
public void setRequest(@RequestBody Object request) {
this.request = request;
}
@Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
logger.info(this.request)
}
}