小编典典

HOWTO使用使用基于Java的注释配置的Spring MVC全局处理404异常

java

我正在构建一个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因为我必须为此创建一个。


阅读 139

收藏
2020-11-16

共1个答案

小编典典

默认情况下,DispatcherServlet不会抛出NoHandlerFoundException您需要启用它。

AbstractAnnotationConfigDispatcherServletInitializer应该让你重写如何DispatcherServlet被创建。这样做并打电话

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