概述
Spring Security
提供了 RequestRejectedHandler
来处理当请求被拒绝时候如何处理,在没有进行配置的情况下,默认是使用 DefaultRequestRejectedHandler
直接将异常进行抛出:
throw requestRejectedException;
同时也提供了 HttpStatusRequestRejectedHandler
来返回对应的状态码。
定制 RequestRejectedHandler
RequestRejectedHandler
的注入是在 WebSecurity
的 setApplicationContext
当中:
try {
this.requestRejectedHandler = applicationContext.getBean(RequestRejectedHandler.class);
}
catch (NoSuchBeanDefinitionException ex) {
}
if (this.requestRejectedHandler != null) {
filterChainProxy.setRequestRejectedHandler(this.requestRejectedHandler);
}
在中的定义为:
private RequestRejectedHandler requestRejectedHandler = new DefaultRequestRejectedHandler();
我们只需要覆盖 Bean
定义即可:
@Bean
RequestRejectedHandler requestRejectedHandler() {
return new CustomizerRequestRejectedHandler();
}
@Slf4j
public class CustomizerRequestRejectedHandler implements RequestRejectedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
RequestRejectedException ex) throws IOException, ServletException {
log.warn("request uri: {},user-agent: {}", request.getRequestURI(), request.getHeader(HttpHeaders.USER_AGENT));
log.error(ex.getMessage(), ex);
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
参考
spring-5-0-3-requestrejectedexception-the-request-was-rejected-because-the-url
log+request+uri+on+RequestRejectedException
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。