如何在Spring Boot中记录无效404请求的请求路径?

时间:2018-11-07 23:24:07

标签: java spring-mvc spring-boot

我尝试了以下操作来记录请求路径,但它们没有提供正确的值。该请求也没有被重定向。

@Controller
@ApiIgnore
public class AppController implements ErrorController{

  @RequestMapping("/error")
  public void invalidRequest(HttpServletRequest request, HttpServletResponse response){

    CustomLogger.error(TAG, "invalidRequest()", "invalid request: " + request.getHeader("path"));
    CustomLogger.error(TAG, "invalidRequest()", "invalid request: " + request.getPathInfo());
    CustomLogger.error(TAG, "invalidRequest()", "invalid request: " + request.getPathTranslated());
    CustomLogger.error(TAG, "invalidRequest()", "invalid request: " + request.getContextPath());
    CustomLogger.error(TAG, "invalidRequest()", "invalid request: " + request.getServletPath());
    ...
  }

  @Override
  public String getErrorPath() {
    return "/error";
  }

提出请求后,我得到

$ curl -i localhost:8080/static/img/notthere.png
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Length: 27
Date: Wed, 07 Nov 2018 23:13:30 GMT

This is not a valid request

这是日志中打印的内容:

2018-11-07 18:13:30.967 ERROR 14432 --- [nio-8080-exec-1] c.s.s.apis.AppController  : invalid request: null
2018-11-07 18:13:30.968 ERROR 14432 --- [nio-8080-exec-1] c.s.s.apis.AppController  : invalid request: null
2018-11-07 18:13:30.968 ERROR 14432 --- [nio-8080-exec-1] c.s.s.apis.AppController  : invalid request: null
2018-11-07 18:13:30.969 ERROR 14432 --- [nio-8080-exec-1] c.s.s.apis.AppController  : invalid request:
2018-11-07 18:13:30.969 ERROR 14432 --- [nio-8080-exec-1] c.s.s.apis.AppController  : invalid request: /error

1 个答案:

答案 0 :(得分:1)

您可以使用Request Dispatcher here

来获取实际的uri。
request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);