我需要在日志中获取触发[NOT FOUND 404]错误的URI。 我使用 .getHeader(HttpHeaders.REFERER) ,但我得到的是null。我尝试使用 getRequestURL() 的方法相同,并且正在获取@RequestMapping方法“ / error”的路径。
例如: 如果用户输入:mywebsite.com/fdsfihdif并且没有这样的地址,我应该在这样的日志中看到此 [NOT FOUND 404]用户[john@yahoo.com]试图访问此URI: [mywebsite.com/fdsfihdif]
这是我的errorControler:
@Controller
public class CustomErrorController implements ErrorController {
private static final Logger log = LogManager.getLogger(CustomErrorController.class);
@RequestMapping("/error")
public String handleError(HttpServletRequest request) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (status != null) {
Integer statusCode = Integer.valueOf(status.toString());
if (statusCode == HttpStatus.NOT_FOUND.value()) {
//404 with the wrong URI entered by user
log.error("[NOT FOUND 404] User [" + auth.getName() + "] tried to access this URL : ["+ request.getRequestURL() +"] : [" + request.getHeader(HttpHeaders.REFERER) + "]";
return "errors/404";
} else {
//something else
return "errors/error";
}
}
return "error";
}
@Override
public String getErrorPath() {
return "/error";
}
}
以下是输出:
2018-06-22 18:48:59.507错误 [nio-9090-exec-7] c.b.g.c.CustomErrorController
MSG ==> [找不到404]用户[dumi7ru]尝试访问此URL:[http://localhost:9090/error]:[null]
答案 0 :(得分:1)
您可以将原始URI作为
String originalUri = request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
在堆栈web.xml 404 redirect to servlet, how to get the original URI?上的类似查询