设置throwExceptionIfNoHandlerFound
在Spring 4.2.2中没有效果。这对我来说很重要,因为我必须将所有响应作为JSON发送。设置throwExceptionIfNoHandlerFound在Spring 4.2中没有效果。*
我设置throwExceptionIfNoHandlerFound
在我AppInitializer这样的:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
[...]
@Override
protected void customizeRegistration(Dynamic registration) {
boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); // -> true
if(!done) throw new RuntimeException();
}
}
它似乎工作,因为DispatcherServlet#noHandlerFound抛出异常像预期:
// https://github.com/spring-projects/spring-framework/blob/4.2.x/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java#L1013
protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (pageNotFoundLogger.isWarnEnabled()) {
pageNotFoundLogger.warn("No mapping found for HTTP request with URI [" + getRequestUri(request) +
"] in DispatcherServlet with name '" + getServletName() + "'");
}
if (this.throwExceptionIfNoHandlerFound) {
throw new NoHandlerFoundException(request.getMethod(), getRequestUri(request),
new ServletServerHttpRequest(request).getHeaders());
}
else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
但后来(这是非常混乱! )每个例外get catched和resolved to an error view。因此,它是不可能通过春季 - @ExceptionHandler
处理NoHandlerFoundException
问:
我敢肯定,这是非常好的,有用的功能,但它是没有办法检测404错误发送自定义响应而不是默认的html错误页面?
具有相同的问题。你有办法做到这一点吗? – rpvilao
@rpvilao,我也有同样的问题,你们都解决了吗? – karfai
不记得确切,但我已经在下面回答了这个问题。我可能在这里找到答案:http://stackoverflow.com/questions/30504905/handle-error-404-in-web-application-not-rest-application – rpvilao