我正在构建一个Spring 4 MVC应用程序。并且它是使用Java注释完全配置的。没有web.xml。该应用是使用的实例进行配置的AbstractAnnotationConfigDispatcherServletInitializer,WebMvcConfigurerAdapter就像这样,
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页添加全局/全部捕获异常处理程序,HttpStatus.NOT_FOUND但没有成功。以下是我尝试过的一些方法。
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因为我必须为此创建一个。
默认情况下,DispatcherServlet不会抛出NoHandlerFoundException。您需要启用它。
DispatcherServlet
NoHandlerFoundException
本AbstractAnnotationConfigDispatcherServletInitializer应该让你重写如何DispatcherServlet被创建。这样做并打电话
DispatcherServlet dispatcherServlet = ...; // might get it from super implementation dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);