查找最简单的方法是使用以下命令:
@ExceptionHandler(Throwable.class)
public String handleAnyException(Throwable ex, HttpServletRequest request) {
return ClassUtils.getShortName(ex.getClass());
}
如果URL在DispatcherServlet的范围内,则任何由于错误输入或其他原因引起的404都将被此方法捕获,但是如果键入的URL超出DispatcherServlet的URL映射,则你必须使用以下任一方法:
<error-page>
<exception-type>404</exception-type>
<location>/404error.html</location>
</error-page>
要么
为你的DispatcherServlet映射URL提供“ /”映射,以便处理特定服务器实例的所有映射。
我使用spring 4.0和java配置。我的工作代码是:
@ControllerAdvice
public class MyExceptionController {
@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handleError404(HttpServletRequest request, Exception e) {
ModelAndView mav = new ModelAndView("/404");
mav.addObject("exception", e);
//mav.addObject("errorcode", "404");
return mav;
}
}
在JSP中:
<div class="http-error-container">
<h1>HTTP Status 404 - Page Not Found</h1>
<p class="message-text">The page you requested is not available. You might try returning to the <a href="<c:url value="/"/>">home page</a>.</p>
</div>
对于初始化参数配置:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
public void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
}
}
或通过xml:
<servlet>
<servlet-name>rest-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>throwExceptionIfNoHandlerFound</param-name>
<param-value>true</param-value>
</init-param>
</servlet>