1

设置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 catchedresolved to an error view。因此,它是不可能通过春季 - @ExceptionHandler处理NoHandlerFoundException

问:

我敢肯定,这是非常好的,有用的功能,但它是没有办法检测404错误发送自定义响应而不是默认的html错误页面?

+0

具有相同的问题。你有办法做到这一点吗? – rpvilao

+0

@rpvilao,我也有同样的问题,你们都解决了吗? – karfai

+0

不记得确切,但我已经在下面回答了这个问题。我可能在这里找到答案:http://stackoverflow.com/questions/30504905/handle-error-404-in-web-application-not-rest-application – rpvilao

回答

1

当我们重写使用默认的servlet处理似乎会发生。 Answered here

+0

尽管这个链接可能回答这个问题,但最好在这里包含答案的重要部分,并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/ review/low-quality-posts/18817429) –