【发布时间】:2014-08-21 07:53:04
【问题描述】:
我正在构建一个 Spring 4 MVC 应用程序。它完全使用 Java Annotations 进行配置。没有web.xml。该应用程序是通过使用AbstractAnnotationConfigDispatcherServletInitializer 和WebMvcConfigurerAdapter 的实例来配置的,如下所示,
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.example.*"})
@EnableTransactionManagement
@PropertySource("/WEB-INF/properties/application.properties")
public class WebAppConfig extends WebMvcConfigurerAdapter {
...
}
和
public class WebAppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
...
}
我现在正在尝试为 404 页添加一个全局/catch-all 异常处理程序,即HttpStatus.NOT_FOUND,但没有成功。以下是我尝试的一些方法。
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
@ControllerAdvice
public class GlobalExceptionHandlerController {
@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public ModelAndView handleException (NoSuchRequestHandlingMethodException ex) {
ModelAndView mav = new ModelAndView();
return mav;
}
@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public ModelAndView handleExceptiond (NoHandlerFoundException ex) {
ModelAndView mav = new ModelAndView();
return mav;
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public void handleConflict() {
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoSuchRequestHandlingMethodException.class)
public void handlesdConflict() {
}
}
这些方法都不会被执行。我不知道如何处理这个问题。我不想使用web.xml,因为我必须为此创建一个。
【问题讨论】:
-
我不知道他们为什么没有通过一些
protected方法使DispatcherServlet可见,但自定义解决方案似乎不错。 -
为什么不直接覆盖 createDispatcherServlet
标签: java spring spring-mvc http-status-code-404 web.xml