我正在构建一个Spring 4 MVC应用程序。并且它是使用Java注释完全配置的。没有web.xml。像这样使用AbstractAnnotationConfigDispatcherServletInitializerWebMvcConfigurerAdapter实例配置该应用,

@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,但没有成功。以下是我尝试过的一些方法。
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,因为那样我就必须为此创建一个。

最佳答案

By default, the DispatcherServlet does not throw a NoHandlerFoundException .您需要启用它。
AbstractAnnotationConfigDispatcherServletInitializer应该让您覆盖DispatcherServlet的创建方式。这样做并打电话

DispatcherServlet dispatcherServlet = ...; // might get it from super implementation
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);

07-28 03:22
查看更多