【发布时间】:2017-08-26 13:04:54
【问题描述】:
我正在尝试在使用 Java 配置完全配置的 Spring MVC 应用程序中使用 @ControllerAdvice 处理 404 错误。
这里有我的conf:
public class WebAppInitializer implements WebApplicationInitializer
{
@Override
public void onStartup(ServletContext container)
{
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(WebMvcConfig.class);
dispatcherServlet.setServletContext(container);
dispatcherServlet.refresh();
CookieHelper cookie = (CookieHelper) dispatcherServlet.getBean("cookie");
final Gson gson = (Gson) dispatcherServlet.getBean("gson");
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
dispatcher.addMapping("/");
dispatcher.setLoadOnStartup(1);
dispatcher.setInitParameter("throwExceptionIfNoHandlerFound", "true");
FilterRegistration.Dynamic filter = container.addFilter("BaseFilter", new BaseFilter(cookie, gson));
filter.setInitParameter("forceEncoding", "true");
filter.addMappingForUrlPatterns(null, true, "/coolers/*");
filter.addMappingForUrlPatterns(null, true, "/hothouses/*");
filter.addMappingForUrlPatterns(null, true, "/lang/*");
filter.addMappingForUrlPatterns(null, true, "/organizations/*");
filter.addMappingForUrlPatterns(null, true, "/reworks/*");
filter.addMappingForUrlPatterns(null, true, "/select/*");
filter.addMappingForUrlPatterns(null, true, "/volumes/*");
}
}
还有我的 GlobalExceptionHandlerController:
@ControllerAdvice
public class GlobalExceptionHandlerController
{
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handle() {
System.out.println("test test test test");
return "error/index";
}
}
NoHandlerFoundException 没有触发?
【问题讨论】:
-
您是否正在执行任何会导致 NoHandlerFoundException 的操作?
-
即使线程较旧,遇到相同的情况,写下答案,以便它可以帮助其他人。
标签: java spring exception http-status-code-404